Java intタイプのうち1の個数

912 ワード

private int getCountOfOne(int x){
    int result = 0;
    while(x != 0){
        x = (x - 1) & x;
        result++;
    }
    
    return result;
}
例題:
正の整数があります。バイナリ表現の中で1の個数が同じで、サイズが一番近い二つの数を探してください。一つはやや大きく,一つはやや小さい。
与えられた正の整数int xは、求められた2つの数(小さいものは前)を表す整数配列を返してください。答案の存在を保証する。
試験例:2
戻る:[1,4]
import java.util.*;
 
public class CloseNumber {
    public int[] getCloseNumber(int x) {
        int big = x+1, small = x-1;
        while(getCountOfOne(x)!=getCountOfOne(big)){
            big++;
        }
        while(getCountOfOne(x)!=getCountOfOne(small)){
            small--;
        }
        int[] arr = {small,big};
        return arr;// write code here
    }
     
    private int getCountOfOne(int x){
        int result = 0;
        while(x!=0){
            result++;
            x=(x-1)&x;
        }
        return result;
    }
}