-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary representation of next number
53 lines (43 loc) · 1.21 KB
/
Binary representation of next number
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
//Binary representation of next number
import java.io.*;
import java.util.*;
class GfG {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0) {
String s = sc.next();
Solution ob = new Solution();
System.out.println(ob.binaryNextNumber(s));
}
}
}
class Solution {
String binaryNextNumber(String s) {
boolean indication = true;
char[] temp = s.toCharArray();
for(int i = s.length() - 1; i >= 0; i--) {
if(temp[i] == '0') {
temp[i] = '1';
indication = false;
break;
}
else {
temp[i] = '0';
}
}
StringBuilder ans = new StringBuilder();
if(indication == true) {
ans.append('1');
ans.append(temp);
}
else {
int index = 0;
while(index < s.length() && temp[index] == '0') {
index++;
}
ans.append(temp, index, s.length() - index);
}
return ans.toString();
}
}