C++中下一個數的二進位制表示
在這個問題中,我們給定一個數字的二進位制表示,我們需要找到下一個數字的二進位制表示,即在給定數字上加1後得到的結果。
二進位制表示是指將數字的基數更改為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加到數字上時,從右開始的所有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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP