-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary representation of next number.cpp
64 lines (52 loc) · 1.25 KB
/
Binary representation of next number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
string binaryNextNumber(string s) {
// code here.
string ans="";
int carry=1;
int i=s.length()-1;
while(i>=0 || carry>0){
if(i>=0 && s[i]=='1' && carry==1){
carry=1;
ans+='0';
}else if(i>=0 && s[i]=='0' && carry==1){
ans+='1';
carry=0;
}else if(i>=0 && s[i]=='1' && carry==0){
ans+='1';
}else if(carry==1) {
ans+='1';
carry=0;
}else {
ans+='0';
}
i--;
}
reverse(ans.begin(),ans.end());
string temp="";
i=0;
while(i<ans.length() && ans[i]=='0') i++;
while(i<ans.length()){
temp+=ans[i];i++;
}
return temp;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
Solution ob;
cout << ob.binaryNextNumber(s);
cout << "\n";
}
return 0;
}
// } Driver Code Ends