[LeetCode]338. Counting Bits

来源:互联网 发布:mac 树状笔记 编辑:程序博客网 时间:2024/04/20 11:54

Problem Description

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.
[https://leetcode.com/problems/counting-bits/]

思路

DP。
对于一个数,如果他是偶数,那它二进制后含有‘1’的个数与左移一位之后含有‘1’的个数相同,如果是奇数,则加1。
例如:
偶数1100110中含有的1与110011相同
奇数1100111中含有的1比110011多1.

Code

package q338;public class Solution {    public int[] countBits(int num) {        int[] ans=new int[num+1];        ans[0]=0;        for(int i=1;i<=num;i++){            ans[i]=ans[i-1]>>1+i%2;        }        return ans;    }}
0 0
原创粉丝点击