Problem Solving/Programmers
[Level 2] 2개 이하로 다른 비트
kmkunk
2022. 4. 6. 12:52
class Solution {
public long[] solution(long[] numbers) {
long[] answer = new long[numbers.length];
for(int i=0; i<numbers.length; i++) {
if(numbers[i]%2==0) { answer[i] = numbers[i]+1; }
else {
String[] arr = Long.toBinaryString(numbers[i]).split("");
String s = "";
int k = -1;
for(int j=0; j<arr.length; j++) {
if(arr[j].equals("0")) { k = j; }
}
if(k==-1) {
s = "10";
for(int j=0; j<arr.length-1; j++) { s += "1"; }
} else {
arr[k] = "1"; arr[k+1] = "0";
for(int j=0; j<arr.length; j++) { s += arr[j]; }
}
answer[i] = Long.valueOf(s, 2);
}
}
return answer;
}
}