C ++中先前数字的二进制表示

在这个问题中,我们得到一个数字的二进制表示形式,我们必须找到前一个数字的二进制表示形式,即从给定数字中减去一个数字后得到的数字。

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

例如,23的二进制表示形式是10111。

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

为了解决这个问题,我们需要了解二进制减法的基础。让我们看看以二进制形式从0或1中减去1时会发生什么.0-1 = 1 = 1 + 1从下一位进位。1-1 = 0。

让我们举个例子来更好地理解问题,

Input : 101101100
Output : 101101011
Explanation : (101101100)2 Is the binary representation of 364. The number preceding it is 363 whose
binary representation is (101101011)2 . we have used binary subtraction here and subtracted (1)2 
from the binary representation of the number to yield the result .

让我们看看该程序背后的逻辑,然后我们将基于我们的逻辑设计一个算法。在这里,我们需要从数字的二进制表示中减去一个。为此,我们将从右边开始,将所有零翻转为1,直到遇到1。当遇到1时,我们将1翻转为0并返回最终结果。

算法

Step 1 : Start right to left i.e n-1 to 0.
Step 2 : If 1 is encounter change it to 0 and break.
Step 3 : If 0 is encountered, change it 1.
Step 4 : Print the array.

示例

上述算法的程序实现-

#include <bits/stdc++.h>
using namespace std;
string previousNumber(string num) {
   int n = num.size();
   if (num.compare("1") == 0)
      return "0";
      int i;
   for (i = n - 1; i >= 0; i--) {
      if (num.at(i) == '1') {
         num.at(i) = '0';
         break;
      } else
      num.at(i) = '1';
   }
   if (i == 0)
      return num.substr(1, n - 1);
      return num;
}
int main() {
   string number = "1011011000";
   cout<<"the Binary representation of the number is "<<number<<endl;
   cout<<"Binary representation of previous number is "<<previousNumber(number);
   return 0;
}

输出结果

The Binary representation of the number is 1011011000
Binary representation of previous number is 1011010111