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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值