• LeetCode: 338. Counting Bits


    338. Counting Bits

    Description

    Given a non-negative integer number num. For every number i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

    Example:
    For num = 5 you should return [0,1,1,2,1,2].

    题目大概意思是,=:给定一个非负整数num,要求输出从0到num中每个数二进制中1的个数,例如0二进制中1的个数为0,1二进制中1的个数为1,2二进制中1的个数为1,3二进制中1的个数为2。如果num=3,则输出[0,1,1,2]

    my program

    class Solution {
    public:
        int Count(int num)
        {
            int n = 0;
            while (num)
            {
                ++n;
                num = num & (num -1);
            }
            return n;
        }
        vector<int> countBits(int num) {
            vector<int> result;
            for (int i=0; i<=num; ++i)
            {
                result.push_back(Count(i));
            }
            return result;
        }
    };

    Submission Details
    15 / 15 test cases passed.
    Status: Accepted
    Runtime: 73 ms
    You are here!
    Your runtime beats 51.45% of cpp submissions.

    评价:中规中矩的方法,一个计算输入数二进制中1的个数的函数,从0循环到num将每个数中的1的个数分别压入vector result 中,最后返回结果数组。

    other better algorithm

    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> ret(num+1, 0);
            for (int i = 1; i <= num; ++i)
                ret[i] = ret[i&(i-1)] + 1;
            return ret;
        }
    };
    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> ret(num+1, 0);
            for(int i=1; i<=num; ++i)
                ret[i] = ret[i>>1] + i%2;
            return ret;
        }
    };

    用到了动态规划。
    数组中存储了之前的结果,①当前的i二进制中1的个数等于i&(i-1)二进制中的个数再+1;
    或者是②i二进制中1的个数等于i/2二进制的个数再+i%2(即如果i是偶数,那么i二进制中1的个数就等于i/2二进制中1的个数,如果i是奇数,那么i二进制的个数就等于i/2二进制中个数再+1);

  • 相关阅读:
    获取cookie
    EF数据迁移(当模型改变时更新数据库)
    EF有外键的查询
    EF查询
    前台主页面给子页面赋值(回调)
    jquery取元素值
    chart画图
    IIS 7.0 的 ASP.NET 应用程序生命周期概述(转载)
    查询服务器登录个数
    gridview中判断隐藏还是现实
  • 原文地址:https://www.cnblogs.com/yangjiannr/p/7391354.html
Copyright © 2020-2023  润新知