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

    原文地址:https://www.jianshu.com/p/92e3e5a7df5d

    时间限制:1秒 空间限制:32768K

    题目描述

    求出任意非负整数区间中1出现的次数(从1到n中1出现的次数)。

    我的代码

    class Solution {
    public:
        int NumberOf1Between1AndN_Solution(int n)
        {
            /*若要计算百位上1出现的次数,
            它受到了3方面的影响:百位上的数字、百位以下低位上的数字、百位以上高位上的数字。
            当百位上数字是0时,受高位数字影响;
            当百位上数字是1时,受高位和低位数字影响;
            当百位上的数字是2-9时,受高位数字影响。*/
            if(n<0)
                throw n;
            int i=1,res=0;
            int cur=0,low=0,high=0;
            while(n/i){
                cur=(n/i)%10;
                low=n-i*(n/i);
                high=(n/i)/10;
                if(cur==0)
                    res+=high*i;
                else if(cur==1)
                    res+=high*i+low+1;
                else
                    res+=(high+1)*i;
                i*=10;
            }
            return res;
        }
    };
    

    运行时间:3ms
    占用内存:472k

  • 相关阅读:
    求数组元素出现的次数
    数组的一些内置方法
    二维数组
    创建对象
    取出数组最大值与最小值
    4-jQuery
    3-jQuery
    2-jQuery
    1-jQuery
    Spark共享变量(广播变量、累加器)
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10822245.html
Copyright © 2011-2022 走看看