
내가 작성한 코드
class Solution {
public int solution(int n) {
int countOne = Integer.bitCount(n);
while (true) {
n++;
if (Integer.bitCount(n) == countOne) {
return n;
}
}
}
}
Integer.bitCount(정수)
: 정수를 2진법으로 변환한 뒤 1의 갯수를 세는 함수
다른 사람의 코드
class Solution {
public int solution(int n) {
int postPattern = n & -n; // 가장 낮은 비트 추출
// XOR 연산을 수행하여 두 값의 차이를 계산
// XOR 결과를 postPattern으로 나누고 2비트 오른쪽으로 이동
int smallPattern = ((n ^ (n + postPattern)) / postPattern) >> 2;
// n + postPattern에 smallPattern을 OR 연산하여 결과를 반환
return n + postPattern | smallPattern;
}
}
Share article