LeetCode 338

来源:互联网 发布:python怎么取最大 编辑:程序博客网 时间:2024/05/01 15:10

338. Counting Bits

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].


思路 递归的分区 [2-3] [4-7] [7-15]等

public class Solution {    public int[] countBits(int num) {        int[] result = new int[num+1];        for(int i = 0;i <= num;i++){            result[i] = get(i);        }        return result;    }        public int get(int num){        if(num == 0){            return 0;        }else if(num == 1){            return 1;        }else{            return 1 + get(num - max(num));        }    }        public int max(int num){        int count = 0;        while(num != 1){            num /= 2;            count++;        }        return (int) Math.pow(2,count);    }}


0 0
原创粉丝点击