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

    输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
    例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。

    示例 1:
    输入:n = 12
    输出:5

    示例 2:
    输入:n = 13
    输出:6

    限制:
    1 <= n < 2^31

    1、暴力

    class Solution {
        public int countDigitOne(int n) {
            int res=0;
            for(int i=1;i<=n;i++){
                int temp=i;
                while(temp/10!=0){
                    if(temp%10==1){
                        res++;
                    }
                    temp/=10;
                }
            }
            return res;
        }
    }
    

    2、找规律

    class Solution {
        public int countDigitOne(int n) {
            int digit=1,res=0;
            int high=n/10,cur=n%10,low=0;
            while(high!=0 || cur!=0){
                if(cur==0){
                    res+=digit*high;
                }else if(cur==1){
                    res+=digit*high+low+1;
                }else{
                    res+=digit*(high+1);
                }
                low+=cur*digit;
                cur=high%10;
                high=high/10;
                digit*=10;
            }
            return res;
        }
    }
    
  • 相关阅读:
    Spring_IOC理论推导
    第一个Mybatis及运行问题分析
    Spring_简介
    ECharts_雷达图
    ECharts_饼图
    ECharts_直角坐标系的常用配置
    ECharts_散点图
    ECharts_折线图
    util之日期工具类
    util之Json工具类
  • 原文地址:https://www.cnblogs.com/xyz-1024/p/14434175.html
Copyright © 2011-2022 走看看