zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    

      

  • 相关阅读:
    linux 内核配置
    使用 git 下载linux 源码
    订阅 linux 邮件列表注意的问题
    使用反射创建一维数组和二维数组
    反射API
    反射机制
    集合案例--对ArrayList容器中的内容进行排序
    Collections
    TreeSet
    Set容器
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8758992.html
Copyright © 2011-2022 走看看