leetcode 338. Counting Bits

来源:互联网 发布:男士帽子 知乎 编辑:程序博客网 时间:2024/04/26 05:56

分析

打算用动态规划,所以先找x和x-1的规律:
0
1
10
11
100
101
110
111
1000
1001
1010
1010010100101
1010010100110
111
1000

f(x) 表示x二进制表示中1的个数, m表示从右往左第一个0的位置(从0开始计数)。

找数字x-1 从右往左第一个0的位置m;

f(x) = f(x-1) - m + 1;

我们认为7这样的数字的二进制表示中没有0,如果x-1的二进制表示中没有找到0,则:

f(x) = 1;

代码

public class Solution {    public int findZeroFromRight(int n){        int ans = 0;        while(n % 2 == 1){            n = n >> 1;            ans++;        }        if(n == 0)            return -1;//表示n的二进制表示中没有0        else            return ans;    }    public int[] countBits(int num) {        int ans[] = new int[num+1];        ans[0] = 0;        for(int i = 1; i <= num; i++){            int m = findZeroFromRight(i-1);            if(m == -1){                ans[i] = 1;            }            else{                ans[i] = ans[i-1] - m + 1;            }        }        return ans;    }}
0 0
原创粉丝点击