剑指Offer 刷题 从1到n整数中1出现的次数

求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)
来自:https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?tpId=13&&tqId=11184&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
剑指Offer 刷题 从1到n整数中1出现的次数_第1张图片

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
    //求每个位的数字所用
        int index = 1;
        //记录1的个数
        int count = 0;
        int high = n,cur = 0,low = 0;
        //由于high = n /(index*10) 中index *10 很容易越位
        //特修改如下
        while(high > 0){
            high /= 10;
            cur = (n / index) % 10;
            low = n - (n / index) * index;
            //以下是计算的公式
            //当 cur = 0 时: 此位 1 的出现次数只由高位high 决定,计算公式为
            if(cur == 0) count += high * index;
            //当cur=1 时: 此位 1 的出现次数由高位high 和低位low 决定,计算公式为
            if(cur == 1) count += high * index + low + 1;
            //当 cur>1 时: 此位 11 的出现次数只由高位 high 决定,计算公式为
            if(cur > 1) count += (high+1) * index;
            index *= 10;
        }
        return count;

    }
}

你可能感兴趣的:(剑指Offer)