1. 程式人生 > >劍指offer之 二進制中1的個數

劍指offer之 二進制中1的個數

system 死循環 ble clas pack n) 請實現一個函數 邊界 邊界值

問題描述: 請實現一個函數,輸入一個整數,輸出該數二進制表示中1的個數。例如把9表示成二進制是1001,有2位是1 因此如果輸入9,該函數輸出2;

package Problem10;

public class NumberOf1 {
    /*
     * 問題描述: 請實現一個函數,輸入一個整數,輸出該數二進制表示中1的個數。例如把9表示成二進制是1001,有2位是1 因此如果輸入9,該函數輸出2
     */

    /**
     * @param args
     */
    // 可能引起死循環的解法1
    public static int numberof1_1(int n) {
        int count = 0;
        while (n != 0) {
            if ((n & 1) != 0) {
                count++;
            }
            n = n >> 1;
        }
        return count;
    }

    // 常規解法2
    public static int numberof1_2(int n) {
        int count = 0;
        int flag = 1;
        while (flag != 0) {
            if ((n & flag) != 0) {
                count++;
            }
            flag = flag << 1;
        }
        return count;
    }

    // 解法3:把一個吧整數減去1,再和原整數做位與運算,會把該整數最右邊一個1變成0
    // 一個整數的二進制表示中有多少個1,就可以進行多少次這樣的操作
    public static int numberof1_3(int n) {
        int count = 0;
        while (n != 0) {
            count++;
            n = n & (n - 1);
        }
        return count;
    }

    public static void main(String[] args) {
        NumberOf1 test = new NumberOf1();
        // 測試一下解法1
        System.out.println("解法1:" + test.numberof1_1(9));
        // 測試一下解法2
        System.out.println("解法2:" + test.numberof1_2(100254));
        // 測試一下解法3:正數(邊界值)、負數、0
        System.out.println("解法3:" + test.numberof1_3(0x7FFFFFFF));
        System.out.println("解法3:" + test.numberof1_3(1));
        System.out.println("解法3:" + test.numberof1_3(0x80000000));
        System.out.println("解法3:" + test.numberof1_3(0xFFFFFFFF));
        System.out.println("解法3:" + test.numberof1_3(0));
    }

}

  

劍指offer之 二進制中1的個數