Representación binaria del número anterior

Dada una entrada binaria que represente la representación binaria del número positivo n, encuentre la representación binaria de n-1. Se puede suponer que el número binario de entrada es mayor que 0.
La entrada binaria puede encajar o no incluso en int largo largo sin signo.

Ejemplos: 

Input : 10110
Output : 10101
Here n  = (22)10 = (10110)2
Previous number = (21)10 = (10101)2

Input : 11000011111000000
Output : 11000011110111111

Almacenamos la entrada como una string para que se puedan manejar grandes números. Recorremos la string desde el carácter más a la derecha y convertimos todos los 0 en 1 hasta que encontramos un 1. Finalmente, convertimos el 1 encontrado en 0. El número así formado después de este proceso es el número requerido. Si la entrada es «1», entonces el número anterior será «0». Si solo el primer carácter de toda la string es ‘1’, descartamos este carácter y cambiamos todos los 0 por 1.

Implementación:

C++

// C++ implementation to find the binary
// representation of previous number
#include <bits/stdc++.h>
using namespace std;
 
// function to find the required
// binary representation
string previousNumber(string num)
{
    int n = num.size();
 
    // if the number is '1'
    if (num.compare("1") == 0)
        return "0";
     
    // examine bits from right to left
    int i;
    for (i = n - 1; i >= 0; i--) {
 
        // if '1' is encountered, convert
        // it to '0' and then break
        if (num.at(i) == '1') {
            num.at(i) = '0';
            break;
        }
 
        // else convert '0' to '1'
        else
            num.at(i) = '1';
    }
 
    // if only the 1st bit in the
    // binary representation was '1'
    if (i == 0)
        return num.substr(1, n - 1);
 
    // final binary representation
    // of the required number
    return num;
}
 
// Driver program to test above
int main()
{
    string num = "10110";
    cout << "Binary representation of previous number = "
         << previousNumber(num);
    return 0;
}

Java

// Java implementation to find the binary
// representation of previous number
class GFG
{
 
    // function to find the required
    // binary representation
    static String previousNumber(String num)
    {
        int n = num.length();
 
        // if the number is '1'
        if (num.compareTo("1") == 0)
        {
            return "0";
        }
 
        // examine bits from right to left
        int i;
        for (i = n - 1; i >= 0; i--)
        {
 
            // if '1' is encountered, convert
            // it to '0' and then break
            if (num.charAt(i) == '1')
            {
                num = num.substring(0, i) + '0' +
                            num.substring(i + 1);
                 
                // num.charAt(i) = '0';
                break;
            }
             
            // else convert '0' to '1'
            else
            {
                num = num.substring(0, i) + '1' +
                            num.substring(i + 1);
            }
            //num.at(i) = '1';
        }
 
        // if only the 1st bit in the
        // binary representation was '1'
        if (i == 0)
        {
            return num.substring(1, n - 1);
        }
 
        // final binary representation
        // of the required number
        return num;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String num = "10110";
        System.out.print("Binary representation of previous number = "
                + previousNumber(num));
    }
}
 
/* This code contributed by PrinciRaj1992 */

Python3

# Python3 implementation to find the binary
# representation of previous number
 
# function to find the required
# binary representation
def previousNumber(num1):
    n = len(num1);
    num = list(num1);
 
    # if the number is '1'
    if (num1 == "1"):
        return "0";
    i = n - 1;
     
    # examine bits from right to left
    while (i >= 0):
 
        # if '1' is encountered, convert
        # it to '0' and then break
        if (num[i] == '1'):
            num[i] = '0';
            break;
 
        # else convert '0' to '1'
        else:
            num[i] = '1';
        i -= 1;
 
    # if only the 1st bit in the
    # binary representation was '1'
    if (i == 0):
        return num[1:n];
 
    # final binary representation
    # of the required number
    return '' . join(num);
 
# Driver code
num = "10110";
print("Binary representation of previous number =",
                              previousNumber(num));
     
# This code is contributed by mits

C#

// C# implementation to find the binary
// representation of previous number
using System;
 
class GFG
{
 
    // function to find the required
    // binary representation
    static String previousNumber(String num)
    {
        int n = num.Length;
 
        // if the number is '1'
        if (num.CompareTo("1") == 0)
        {
            return "0";
        }
 
        // examine bits from right to left
        int i;
        for (i = n - 1; i >= 0; i--)
        {
 
            // if '1' is encountered, convert
            // it to '0' and then break
            if (num[i] == '1')
            {
                num = num.Substring(0, i) + '0' +
                            num.Substring(i + 1);
                 
                // num.charAt(i) = '0';
                break;
            }
             
            // else convert '0' to '1'
            else
            {
                num = num.Substring(0, i) + '1' +
                            num.Substring(i + 1);
            }
            //num.at(i) = '1';
        }
 
        // if only the 1st bit in the
        // binary representation was '1'
        if (i == 0)
        {
            return num.Substring(1, n - 1);
        }
 
        // final binary representation
        // of the required number
        return num;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String num = "10110";
        Console.Write("Binary representation of previous number = "
                + previousNumber(num));
    }
}
 
// This code contributed by Rajput-Ji

PHP

<?php
// PHP implementation to find the binary
// representation of previous number
 
// function to find the required
// binary representation
function previousNumber($num)
{
    $n = strlen($num);
 
    // if the number is '1'
    if ($num == "1")
        return "0";
    $i = $n - 1;
     
    // examine bits from right to left
    for (; $i >= 0; $i--)
    {
 
        // if '1' is encountered, convert
        // it to '0' and then break
        if ($num[$i] == '1')
        {
            $num[$i] = '0';
            break;
        }
 
        // else convert '0' to '1'
        else
            $num[$i] = '1';
    }
 
    // if only the 1st bit in the
    // binary representation was '1'
    if ($i == 0)
        return substr($num,1, $n - 1);
 
    // final binary representation
    // of the required number
    return $num;
}
 
    // Driver code
    $num = "10110";
    echo "Binary representation of previous number = ".previousNumber($num);
     
// This code is contributed by mits
?>

Javascript

<script>
 
// Javascript implementation to find the binary
// representation of previous number
// function to find the required
// binary representation
function previousNumber(num)
{
    var n = num.length;
 
    // if the number is '1'
    if (num == "1")
        return "0";
     
    // examine bits from right to left
    var i;
    for (i = n - 1; i >= 0; i--) {
 
        // if '1' is encountered, convert
        // it to '0' and then break
        if (num[i] == '1') {
            num[i] = '0';
            break;
        }
 
        // else convert '0' to '1'
        else
            num[i] = '1';
    }
 
    // if only the 1st bit in the
    // binary representation was '1'
    if (i == 0)
        return num.substring(1, n);
 
    // final binary representation
    // of the required number
    return num.join('');
}
 
// Driver program to test above
var num = "10110".split('');
document.write( "Binary representation of previous number = "
     + previousNumber(num));
 
// This code is contributed by rrrtnx.
</script>
Producción

Binary representation of previous number = 10101

Complejidad de tiempo: O (n) donde n es el número de bits en la entrada.

Este artículo es una contribución de Ayush Jauhari . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *