C ++中下一个数字的二进制表示

在这个问题中,我们得到一个数字的二进制表示形式,并且我们必须找到下一个数字的二进制表示形式,即在给定数字加上一个数字后得到的数字。

数字的二进制表示形式是将数字的底数更改为以2为底,并仅使用0或1表示数字。

例如,14的二进制表示形式是1110。

因此,这里我们将得到一个数字,以二进制形式表示n。而且我们必须找到n + 1的二进制表示形式。

要解决此问题,我们需要了解二进制加法的基础知识。让我们看看将1以二进制形式添加到0或1时会发生什么。

0 +1 = 1 

1 +1 = 10

示例

让我们看一个有关如何解决上述问题的示例,

Input: 010010111
Output: 010011000
Explanation : (010010111)2 is the binary representation of 152 and the next number will be 153 
whose binary representation is (010011000)2. We will use binary addition here and add binary (1)2 
to the binary representation of the number.

从上面的示例中,我们可以看到,将二进制数1加到数字后,所有从右开始的数字都将转换为0,直到遇到第一个0并将该0翻转为1。现在让我们为该逻辑创建一个算法。

算法

Step 1 : Start right to left i.e n-1 to 0
Step 2 : If 0 is encountered, change it 1 and break
Step 3 : If one is encounter change it to 0.
Step 4 : When no zero is encountered, add 1 to the start of the array.
Step 5 : Print the array.

示例

现在,让我们看看该算法的代码实现。

#include <bits/stdc++.h>
using namespace std;
string nextBinary(string num) {
   int l = num.size();
   int flag = 0 ;
   for (int i=l-1; i>=0; i--) {
      if (num.at(i) == '0') {
         num.at(i) = '1';
         flag = 1;
         break;
      } else
         num.at(i) = '0';
   }
   if (flag < 0)
      num = "1" + num;
   return num;
}
int main() {
   string number = "0111010111";
   cout<<"The Binary representation of the number is "<<number<<endl;
   cout<<"Binary representation of next number is "<<nextBinary(number);
   return 0;
}

输出结果

The Binary representation of the number is 0111010111
Binary representation of next number is 0111011000