2021215 LeetCode刷题 比特位计数(难度 :单词规律)

题目:

  

给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。

 

示例 1:

输入:n = 2
输出:[0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例 2:

输入:n = 5
输出:[0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

 

code:

  

class Solution {
    public int[] countBits(int n) {
        int[] result = new int[n+1];
        for(int i = 0;i<result.length;i++) {
            result[i]=new Solution().oneCount(i);
        }
        return result;
    }

      int oneCount(int i){
        int count = 0;
        while(i!=0){
            if(i%2!=0) {
                count++;
            }
                i/=2;

        }
        return count;
    }
}

 

执行结果:
通过

添加备注

执行用时:14 ms, 在所有 Java 提交中击败了5.47%的用户
内存消耗:43.5 MB, 在所有 Java 提交中击败了5.01%的用户
通过测试用例:15 / 15

 

 

 

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/counting-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2021-12-15 20:41  skystrivegao  阅读(33)  评论(0)    收藏  举报