码迷,mamicode.com
首页 > 其他好文 > 详细

338. Counting Bits && 191. Number of 1 Bits

时间:2016-06-30 14:28:35      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1‘s in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

 

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?
 
Hide Similar Problems
 (E) Number of 1 Bits
 
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;
    }
}

 

191. Number of 1 Bits

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.

Hide Tags
 Bit Manipulation
 
 
The signed right shift operator ">>" shifts a bit pattern to the right.
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
e.g.
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
 
 
Bit Operators:
http://stackoverflow.com/questions/15457893/java-right-shift-on-negative-number
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
 
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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!