zoukankan      html  css  js  c++  java
  • 56. 从1到n整数中1出现的次数

     https://www.cnblogs.com/wangkundentisy/p/8946858.html

    结论:

    对于数字n,计算它的第i(i从1开始,从右边开始计数)位数上包含的数字1的个数:

    假设第i位上的数字为x的话,则

    1.如果x > 1的话,则第i位数上包含的1的数目为:(高位数字 + 1)* 10 ^ (i-1)  (其中高位数字是从i+1位一直到最高位数构成的数字)

    2.如果x < 1的话,则第i位数上包含的1的数目为:(高位数字 )* 10 ^ (i-1)

    3.如果x == 1的话,则第i位数上包含1的数目为:(高位数字) * 10 ^ (i-1) +(低位数字+1)   (其中低位数字时从第i - 1位数一直到第1位数构成的数字)

    class Solution {
    public:
        int numberOf1Between1AndN_Solution(int n) {
            if( n < 0)
            return 0;
            int i = 1;
            int high = n;
            int cnt = 0;
            while(high != 0)
            {
                high = n / pow(10 ,i);//high表示当前位的高位
                int temp = n / pow(10, i - 1);
                int cur = temp % 10;//cur表示第i位上的值,从1开始计算
                int low = n  - temp * pow(10, i - 1);//low表示当前位的低位
                if(cur < 1)
                {
                    cnt += high * pow(10, i - 1);
                }
                else if(cur > 1)
                {
                    cnt += (high + 1) * pow(10 ,i - 1);
         
                }
                else
                {
         
                    cnt += high * pow(10, i - 1);
                    cnt += (low + 1);
         
                }
                i++;
            }
            return cnt;
                
            }
    };
    

    AcWing 56. 从1到n整数中1出现的次数

    带女朋友搬家新家条件不好,累到女朋友了,让女朋友受苦了,特此明志:每天学习,明年这个时候(20190812)让女朋友住上大房子,永远年轻,永远热泪盈眶,很多人都是这样,他们都把自己当成身在梦中一样,浑浑噩噩地过日子,只有痛苦或爱或危险可以让他们重新感到这个世界的真实。
  • 相关阅读:
    GCD
    SQLite
    将博客搬至CSDN
    Extjs 4 总结
    spring mvc 复杂参数注入
    7/12 聊天室结束
    7/10
    7/6一些知识点
    随便写写
    spring boot 入门操作(三)
  • 原文地址:https://www.cnblogs.com/make-big-money/p/12322270.html
Copyright © 2011-2022 走看看