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

Counting Bits

时间:2016-08-01 01:49:28      阅读:243      评论: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].

From:

1. Naive Solution

We can simply count bits for each number like the following:

 1 public class Solution {
 2     public int[] countBits(int num) {
 3         int[] result = new int[num + 1];
 4 
 5         for (int i = 0; i <= num; i++) {
 6             result[i] = countEach(i);
 7         }
 8 
 9         return result;
10     }
11 
12     public int countEach(int num) {
13         int result = 0;
14 
15         while (num != 0) {
16             if ((num & 1) == 1) {
17                 result++;
18             }
19             num = num >> 1;
20         }
21 
22         return result;
23     }
24 }

2. Improved Solution

For number 2(10), 4(100), 8(1000), 16(10000), ..., the number of 1‘s is 1. Any other number can be converted to be 2^m + x. For example, 9=8+1, 10=8+2. The number of 1‘s for any other number is 1 + # of 1‘s in x.

技术分享

 1 public class Solution {
 2     public int[] countBits(int num) {
 3         int[] result = new int[num + 1];
 4 
 5         int p = 1; // p tracks the index for number x
 6         int pow = 1;
 7         for (int i = 1; i <= num; i++) {
 8             if (i == pow) {
 9                 result[i] = 1;
10                 pow = pow << 1;
11                 p = 1;
12             } else {
13                 result[i] = result[p] + 1;
14                 p++;
15             }
16         }
17         return result;
18     }
19 }

 

Counting Bits

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5724443.html

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