[leetcode-338]Counting Bits(java)
2016-03-27 20:42
716 查看
原文地址:https://leetcode.com/problems/counting-bits/
分析:这道题要求给定N,然后计算从0到N之间所有的数的bit为1的数,并要求时间复杂度为O(N),因此对于每个数,然后求它的bit数的方法是不可取的。
所幸,当我们把数从0到N写出来时很容易发现规律,即对于2^N的数,末尾N-1位的重复规律,正好等于前N-1个数的重复规律,而这时只需要加1即可。
分析:这道题要求给定N,然后计算从0到N之间所有的数的bit为1的数,并要求时间复杂度为O(N),因此对于每个数,然后求它的bit数的方法是不可取的。
所幸,当我们把数从0到N写出来时很容易发现规律,即对于2^N的数,末尾N-1位的重复规律,正好等于前N-1个数的重复规律,而这时只需要加1即可。
public class Solution { public int[] countBits(int num) { int[] res = new int[num + 1]; res[0] = 0; int base = 1;//末尾为1的情况 while(base <= num){ int next = base * 2;//下一个末尾全为0的值 for(int i = base;i<next && i<=num;i++){ res[i] = res[i-base]+1; } base = next; } return res; } }
相关文章推荐
- Thread详解4:线程的优先级
- java基础-003
- 20145313张雪纯 《Java程序设计》第4周学习总结
- java学习--HashMap
- JAVA中Iterator
- jvm(6)-java类文件结构(字节码文件)
- 20160327javaweb 之JSP入门
- 共同学习Spring源码--开篇语
- JDK的安装
- SpringMVC类型转换、数据绑定详解[附带源码分析]
- JAVA常用集合框架用法详解基础篇二之Colletion子接口List
- java实现跨平台
- Java中常见内存泄露和内存溢出错误总结
- JAVA各类框架之选择
- Java 学习笔记
- 20145212 《Java程序设计》第4周学习总结
- 20145304 Java第四周学习报告
- java循环练习:模拟注册以及登陆
- Java之容器
- 初学java之环境变量的配置