zoukankan      html  css  js  c++  java
  • LeetCode Q338 Counting Bits(Medium)

      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.

    Follow up:

    • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
    • Space complexity should be O(n).
    • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

    翻译

    给定一个非负整数 num ,求出 0 至 num 中每个数的二进制中1的个数。

    分析

    解法一:

      暴力算法,用一个函数算出每个数的二进制中 1 的个数,但没有满足题目要求。

    解法二:

      O(n) 的算法,说明算出每一个数的答案必定和前面的有关系。

    二进制                  1的个数

    0000                        0

    0001                        1

    0010                        1

    0011                        2 

    0100                        1

    0101                        2

    0110                        2

    0111                        3

     ……                        ……

      第一种规律,n 的二进制中 1 的个数等于 n-4 的二进制中 1 的个数加一。

      如果把最后一位于前面的分开呢?

     二进制                  1的个数

     000  0                      0

     000  1                      1

     001  0                      1

     001  1                      2 

     010  0                      1

     010  1                      2

     011  0                      2

     011  1                      3

     ……                        ……

      可以发现,右移一位后的数必定比它本身小,所以之前必定算过,也就是每个数只要判断最后一位数和右移一位后的的数含有1的个数。满足题目一切条件

     1 public class Solution 
     2 {
     3     public int[] CountBits(int num) 
     4     {
     5         int[] ret=new int[num+1];
     6         ret[0]=0;
     7         for (int i=1;i<=num;i++) ret[i]=ret[i>>1]+i%2;
     8         return ret;
     9     }
    10 }
  • 相关阅读:
    elasticsearch 启动
    经纬度解析API
    http://t.cn/xxxxx的短链接如何生成?
    IIS+PHP上传文件大小限制和上传时间限制,iis7和iis8上传文件大小限制和上传时间限制
    WIN2003+IIS6环境SSL证书的安装
    如何创建文件名前带点的文件夹,文件夹名字带点
    解决MYSQL的错误:Got a packet bigger than 'max_allowed_packet' bytes
    php 设置临时内存和超时设置脚本最大执行时间
    谷歌地图 API 开发之获取坐标以及街道详情
    隐藏 google 地图 Logo 隐藏 百度 地图 Logo
  • 原文地址:https://www.cnblogs.com/Bita/p/5932307.html
Copyright © 2011-2022 走看看