233 Number of Digit One 数字1的个数

给定一个整数 n,计算所有小于等于 n 的非负数中数字1出现的个数。

例如:

给定 n = 13,

返回 6,因为数字1出现在下数中出现:1,10,11,12,13。

详见:https://leetcode.com/problems/number-of-digit-one/description/

Java实现:

方法一:

class Solution {
    public int countDigitOne(int n) {
        StringBuilder sb=new StringBuilder();
        for(int i=1;i<=n;++i){
            sb.append(i);
        }
        int cnt=0;
        String str=sb.toString();
        for(int i=0;i<str.length();++i){
            if(str.charAt(i)=='1'){
                ++cnt;
            }
        }
        return cnt;
    }
}

方法二:

class Solution {
    public int countDigitOne(int n) {
        int cnt=0;
        for(long m=1;m<=n;m*=10){
            long a=n/m,b=n%m;
            if(a%10==0){
                cnt+=a/10*m;
            }else if(a%10==1){
                cnt+=a/10*m+(b+1);
            }else{
                cnt+=(a/10+1)*m;
            }
        }
        return cnt;
    }
}

 C++实现:

方法一:

class Solution {
public:
    int countDigitOne(int n) {
        int cnt=0;
        for(long long m=1;m<=n;m*=10)
        {
            int a=n/m,b=n%m;
            if(a%10==0)
            {
                cnt+=a/10*m;
            }
            else if(a%10==1)
            {
                cnt+=a/10*m+(b+1);
            }
            else
            {
                cnt+=(a/10+1)*m;
            }
        }
        return cnt;
    }
};

方法二:

class Solution {
public:
    int countDigitOne(int n) {
        int cnt=0;
        for(long long m=1;m<=n;m*=10)
        {
            cnt+=(n/m+8)/10*m+(n/m%10==1)*(n%m+1);
        }
        return cnt;
    }
};

  

原文地址:https://www.cnblogs.com/xidian2014/p/8758992.html