当前位置: 移动技术网 > IT编程>开发语言>PHP > [LeetCode](面试题43)1~n整数中1出现的次数

[LeetCode](面试题43)1~n整数中1出现的次数

2020年07月13日  | 移动技术网IT编程  | 我要评论

题目

输入一个整数 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

解题思路

参考K神思路 面试题43. 1~n 整数中 1 出现的次数

代码

class Solution {
    public int countDigitOne(int n) {
        int res = 0;
        int digit = 1, high = n/10, cur = n%10, low = 0;
        // 当 high 和 cur 同时为 0 时,说明已经越过最高位,因此跳出
        while(high != 0 || cur != 0){
            if(cur==0){
                res += high*digit;
            }else if(cur==1){
                res += high*digit+low+1;
            }else{
                res += (high+1)*digit;
            }
            low += cur*digit;
            cur = high%10;
            high /= 10;
            digit *= 10;
        }
        return res;

    }
}

本文地址:https://blog.csdn.net/zaker123/article/details/107303709

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网