338CountingBits

从1开始,【0】、【1】、【1、2】、【1、2、 2、3】...【2^root, .. 2^root+2^(root-1),.. ,.2^(root+1)】

其中【2^root, .. 2^root+2^(root-1)】重复前面一个区间的序列,【2^root+2^(root-1),.. ,.2^(root+1)】是前面的序列的对应的每个值加1;

余下不足的一个完整区间长度的部分,分为前半部分和后半部分考虑。

public class Solution {
    public int[] countBits(int num) {
        if(num < 0) return null;
        switch(num){
            case 0: return new int[]{0};
            case 1: return new int[]{0, 1};
            case 2: return new int[]{0, 1, 1};
            case 3: return new int[]{0, 1, 1, 2};  //数组赋值与初始化方法
            default :
                int res[] = new int[num+1]; //0~num 总共num+1个元素
                res[0] = 0;
                res[1] = 1;
                res[2] = 1;
                res[3] = 2;
                int i, cur = 3, count;
                int root = (int)Math.floor(Math.log(num+1)/Math.log(2)); // 2^root <= num < 2^(root+1)
                while(cur <= root){ //one range
                    count = (int)Math.pow(2, cur-1); //eles in the range
                    for(i = count; i < count + count/2; i++){
                        res[i] = res[i- count/2];
                        res[i+count/2] = res[i] + 1;
                    }
                    cur++;
                    }
                    cur = (int)Math.pow(2, root);
                    count = num - cur + 1;
                    if(count <= cur/2){
                        for(i = cur; count > 0; i++, count--){
                               res[i] = res[i - cur/2];
                            }
                    } 
                    else{
                        //System.out.println(" " + root);
                        int rem = cur;
                         for(i = rem, cur = 0 ; cur < rem/2; i++, cur++){
                               res[i] = res[i - rem/2];
                            }
                            // System.out.println(i +" " + cur);
                         while(count - cur > 0){
                             res[i] = res[i - rem/2] + 1;
                             i++;
                             count--;
                         }
                    }
                    return res;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值