《剑指Offer》 No.10 二进制中1的个数

2018-12-13  本文已影响2人  苏村的南哥

解法一  运行时间:29m  占用内存:629k

/*
 * 输入一个整数,获取二进制中包含1的个数
 **/
public static int  numberOf1(int n) {
        String s =Integer.toBinaryString(n);
        char[] c =s.toCharArray();
        int j =0;
        for(int i=0;i<c.length;i++){
                if(c[i]=='1'){
                    j++;
                }
        }
        return j;
     }
}
源码分析:
public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
 }
  /**
     * Convert the integer to an unsigned number.
     */

    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
        char[] buf = new char[chars];

        formatUnsignedInt(val, shift, buf, 0, chars);

        // Use special constructor which takes over "buf".
        return new String(buf, true);
    }

代码分析:以二进制(基数 2)无符号整数形式返回一个整数参数的字符串表示形式。

上一篇 下一篇

猜你喜欢

热点阅读