标签:
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
Follow up:
Hint:
public class Solution { public int[] countBits(int num) { int[] ret = new int[num+1]; // f(i) = f(i/2) + i%2. for(int i = 1; i<=num; ++i) ret[i] = ret[i/2]+i%2; return ret; } }
Write a function that takes an unsigned integer and returns the number of ’1‘ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011
, so the function should return 3.
>>
" shifts a bit pattern to the right.>>>
" shifts a zero into the leftmost position, while the leftmost position after ">>"
depends on sign extension.System.out.println(-1 >> 1); //-1
System.out.println(-1 >> 31); //-1
System.out.println(-1 >>> 29); //7
System.out.println(-1 >>> 30); //3
System.out.println(-1 >>> 31); //1
System.out.println(-1 >>> 32); //-1, <=> -1 >>> 0
System.out.println(-1 >>> 33); //2147483647, <=> -1 >>> 1
int n = -15;
System.out.println(Integer.toBinaryString(n));//11111111111111111111111111110001
int m = n >> 1;
System.out.println(m);//-8
System.out.println(n / 2);//-7
System.out.println(Integer.toBinaryString(m));//11111111111111111111111111111000
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int sum = 0; while(n!=0) { sum += n&1; n = n >>> 1; } return sum; } }
338. Counting Bits && 191. Number of 1 Bits
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5629592.html