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 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告