zoukankan      html  css  js  c++  java
  • 剑指31整数中1出现的次数

    题目描述

    求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。

    class Solution {
    public:
     
        
        int NumberOf1Between1AndN_Solution(int n)
        {
          int count=0;
          long long i=1;
          
         for (i=1;i<=n;i*=10){
             //i表示当时分析的是哪一个数位
             int a=n/i,b=n%i;
             count=count+(a+8)/10*i+(a%10==1)*(b+1);
         }
            return count;
        }
    };

    public class Solution {
        public int NumberOf1Between1AndN_Solution(int n) {
        
            int count=0;
            while (n>0){
                String str=String.valueOf(n);
                char [] chars=str.toCharArray();
                for (int i=0;i<chars.length;i++){
                    if (chars[i]=='1')
                        count++;
                }
                n--;
            }
            return count;
        }
    }

    # -*- coding:utf-8 -*-
    class Solution:
        def NumberOf1Between1AndN_Solution(self, n):
            # write code here
            res=0
            tmp=n
            base=1
            while tmp:
                last=tmp%10
                tmp=tmp/10
                res+=tmp*base
                if last==1:
                    res+=n%base+1
                elif last>1:
                    res+=base
                base*=10
            return res

  • 相关阅读:
    mysql中的几种join 及 full join问题
    MySQL基础练习题
    SQL之IFNULL()
    SQL之查找表中字段的值相同的记录
    Mysql之将一张表内容导入另一张表中
    selenium无界面操作浏览器与Chrome Options的启动项设置
    SQL UNION 和 UNION ALL 操作符
    Python断言方法assert
    Python标准库--contextlib模块
    Python标准库--itertools模块
  • 原文地址:https://www.cnblogs.com/hrnn/p/13401775.html
Copyright © 2011-2022 走看看