• [LeetCode]Number of Digit One


    Number of Digit One

    Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

    For example:
    Given n = 13,
    Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

    Hint:Beware of overflow.

    如果计算1-n之间每个数中1的个数,然后相加,这样可以得到结果,但是会时间超限制。

    通过分析可以发现1出现的总数等于个、十、百、千……这些位分别有1的个数相加的和。

    先举个栗子,计算百位1出现的次数。

    假设n=123023,a=1230,b=23,那么百位出现1,百位以上可以是0-122,此时百位以下有0-99,总共有123*100种;

    假设n=123123,a=1231,b=23,那么百位出现1,百位以上可以是0-122,此时百位以下有0-99,外加百位以上123,百位以下0-23,总共有123*100+23+1种;

    假设n=123223,a=1232,b=23,那么百位出现1,百位以上可以是0-123,此时百位以下有0-99,总共有124*100种;

    假设n=123323,同上。

    可以得出规律假设计算百位上出现的1的个数,m=100,a=n/m,b=n%m:

    如果a%10==0,有a/10*m种;

    如果a%10==1,有a/10*m+b+1种;

    如果a%10>=2,有(a/10+1)*m种。

    对于其他位上m不同,规律相同。

     1 class Solution {
     2 public:
     3     int countDigitOne(int n) {
     4         int result=0;
     5         for(long m=1;m<=n;m*=10)
     6         {
     7             int a=n/m;
     8             int b=n%m;
     9             if(a%10==0)
    10             {
    11                 result+=(a/10*m);
    12             }
    13             else if(a%10==1)
    14             {
    15                 result+=(a/10*m+b+1);
    16             }
    17             else
    18             {
    19                 result+=(a/10+1)*m;
    20             }
    21         }
    22         
    23         return result;
    24     }
    25 };
     
  • 相关阅读:
    利用本地浏览器远程服务器上的jupyter notebook
    解决IIS服务器Web访问提示输入密码
    IIS 配置
    override new 关键字的区别
    ASP.NET的网站的设计与优化
    山东人!
    远程连接SQL Server 2000服务器的解决方案
    对软件的新认识
    一个程序员成长的六个阶段
    优秀程序员应当具备的品质
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4734072.html
Copyright © 2020-2023  润新知