600. 不含连续1的非负整数
作者:互联网
给定一个正整数 n,找出小于或等于 n 的非负整数中,其二进制表示不包含 连续的1 的个数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/non-negative-integers-without-consecutive-ones
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Scanner;
class Solution {
public int findIntegers(int num) {
int[] dp = new int[32];
dp[0] = 1;
dp[1] = 2;
dp[2] = 3;
for (int i = 3; i < 32; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
int res = 0;
int pre = 0;
for (int i = 31; i >= 0; --i) {
if (((num >> i) & 1) != 0) {
res += dp[i];
if (pre == 1) {
return res;
}
pre = 1;
} else {
pre = 0;
}
}
return res + 1;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(new Solution().findIntegers(in.nextInt()));
}
}
}
标签:pre,600,非负,int,res,整数,new,dp,Scanner 来源: https://www.cnblogs.com/tianyiya/p/15830439.html