

package com.walegarrett.offer;
/**
 * @Author WaleGarrett
 * @Date 2021/2/8 9:29
 */
/**
 * 题目详情:
 * 输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
 * 例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
 */
public class Offer_43 {
    public int countDigitOne(int n) {
        int high = n/10,cur = n%10, low = 0;
        int digital = 1;//digital表示数位
        int res = 0;//1的个数
        while(high!=0 || cur != 0){
            if(cur == 0){
                res += (high * digital);
            }else if(cur == 1){
                res += (high*digital + low +1);
            }else res += (high+1) * digital;
            low += cur * digital;
            cur = high %10;
            high /=10;
            digital *= 10;
        }
        return res;
    }
}
剑指 Offer 43. 1~n 整数中 1 出现的次数 + 数位模拟 + 思维
原文:https://www.cnblogs.com/GarrettWale/p/14387734.html