[LeetCode]600. Non-negative Integers without Consecutive Ones
来源:互联网 发布:hadoop执行过程源码 编辑:程序博客网 时间:2024/06/05 20:19
https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/#/description
给一个数n,找出有多少个不大于n的正数,且这些正数的二进制表示中不包含两个连续的1
int转2进制string的API!!
先用dp找出在k位二进制长度的数有多少满足条件的。a[i]表示以0为结尾的长度为i + 1的满足条件的数字个数,b[i]表示1为结尾的。
再找a[n - 1] + b[n - 1]里面overcount了多少,只有当连续两位为0时,b[i]是overcount的。11、01、10都能cover到a[i]和b[i]
public class Solution { public int findIntegers(int num) { StringBuilder sb = new StringBuilder(Integer.toBinaryString(num)).reverse(); int n = sb.length(); int[] a = new int[n]; int[] b = new int[n]; a[0] = 1; b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i - 1] + b[i - 1]; b[i] = a[i - 1]; } int res = a[n - 1] + b[n - 1]; for (int i = n - 2; i >= 0; i--) { if (sb.charAt(i) == '0' && sb.charAt(i + 1) == '0') { res -= b[i]; } if (sb.charAt(i) == '1' && sb.charAt(i + 1) == '1') { break; } } return res; }}
阅读全文
0 0
- 【LeetCode】600. Non-negative Integers without Consecutive Ones
- Leetcode 600. Non-negative Integers without Consecutive Ones
- [LeetCode]600. Non-negative Integers without Consecutive Ones
- leetcode 600. Non-negative Integers without Consecutive Ones
- [leetcode]600. Non-negative Integers without Consecutive Ones
- LeetCode 600. Non-negative Integers without Consecutive Ones 题解
- 600. Non-negative Integers without Consecutive Ones
- 600. Non-negative Integers without Consecutive Ones
- 600. Non-negative Integers without Consecutive Ones
- Leetcode 600 Non-negative Integers without Consecutive Ones
- leetcode 552. Student Attendance Record II & 600. Non-negative Integers without Consecutive Ones
- leetcode 600. Non-negative Integers without Consecutive Ones 非负整数不包括连续的1 + DP动态规划
- 第十五周:( LeetCode600) Non-negative Integers without Consecutive Ones(c++)
- LEETCODE--Max Consecutive Ones
- LeetCode: Max Consecutive Ones
- 【leetcode】Max Consecutive Ones
- LeetCode:Max Consecutive Ones
- LeetCode Max Consecutive Ones
- Vue.js的全局/局部组件填坑记
- test
- 安卓开发之自定义相机时图片变形问题
- 树学习(6)
- struts、spring 源码下载地址
- [LeetCode]600. Non-negative Integers without Consecutive Ones
- user版本qcom-system-daemon不编译问题
- Android控件TextView的实现原理分析
- ubuntu第一天
- 监控sql apply过程
- 【ActiveMQ】activemq 三种消息监听器
- Java引用总结--StrongReference、SoftReference、WeakReference、PhantomReference
- Android中使用系统api申请开启权限
- 如何在不改SQL的情况下优化数据库