1. 程式人生 > 其它 >LeetCode:計算給定數字其前面所有二進位制中1的數目

LeetCode:計算給定數字其前面所有二進位制中1的數目

技術標籤:LeetCode動態規劃演算法leetcodejava

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 1:
Input:2
Output:[0,1,1]

Example 2:
Input:5
Output:[0,1,1,2,1,2]

題目大意:
給定一個非負整數num.對於0<=i<=num範圍中的每個數字i,計算二進位制中的1數目並將它作為陣列返回.

解題思路:
方法1:動態規劃+最低有效位(去掉)
最直觀的做法是利用二進位制的思路,i向右移動一位之後有多少個1,並判斷此時i的最後一位是否為1,即動態規劃,
狀態轉移方程為:p(x)=p(x/2)+(x mod 2);

方法2:動態規劃+最高有效位(去掉)
狀態轉移方程:P(x+b)=P(x)+1,b=2^m>x;

Go語言實現

package main

import "fmt"

func countBits(num int)[]int{
	ans:=make([]int,num+1)
	ans[0]=0
	for i:=1;i<=num;i++{
		ans[i]=i&1+ans[i>>1]
	}
	return ans
}

func countBits1(num int)[]int{
	ans:=make([]int,num+1)
	i,b:=0,1
	for b<=num{
		for i<b&&i+b<=num{//generate [b,2b) or [b,num) from [0,b)
			ans[i+b]=ans[i]+1
			i++
		}
		i=0
		b<<=1 //b=2b
	}
	return ans
}
func main(){
	fmt.Println(countBits(4))
}

Java語言實現

/*
* 動態規劃+設定最後位
* 從右到左設定第一個為1的位置,即狀態方程為:p(x)=P(x&(x-1))+1,其中x&(x-1)是將最低位第一個為1的清零.
* */

public class countBits {
    public int[] countBit(int num){
        int[] res=new int[num+1];
        res[0]=0;
        for(int i=1;i<=num;++i){
            res[i]=res[i&(i-1)]+1;
        }
        return res;
    }

    public static void main(String[] args){
        int[] ans=new countBits().countBit(5);
        for(int i:ans){
            System.out.printf("%d ",i);
        }
    }
}