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


在这个问题中,我们给定一个数字的二进制表示,我们需要找到前一个数字(即从给定数字中减去 1 后得到的数字)的二进制表示。

数字的**二进制表示**是将数字的基数更改为 2,并仅使用 0 或 1 来表示该数字。

例如,23 的二进制表示为 10111。

因此,这里我们将得到一个数字,例如用二进制形式表示的 n。我们需要找到 n-1 的二进制表示。

要解决这个问题,我们需要了解二进制减法的基础知识。让我们看看当从二进制形式的 0 或 1 中减去 1 时会发生什么。0 - 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

更新于:2020年7月9日

245 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.