zoukankan      html  css  js  c++  java
  • [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 };
     
  • 相关阅读:
    Linux后台进程管理的一些命令小结
    Linux 技巧:让进程在后台可靠运行的几种方法
    python对图片进行分割
    pytorch实现优化optimize
    pytorch实现批训练
    pytorch实现网络的保存和提取
    pytorch实现分类
    pytorch实现回归任务
    递推之数字三角形
    深搜——蓝桥杯之迷宫
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4734072.html
Copyright © 2011-2022 走看看