根据中间位的取值来分类讨论

整数中1出现的次数(从1到n整数中1出现的次数)

http://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6

根据中间位的取值来分类讨论。

image-20200906171104821
大佬的思路:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/

    /**
     * 从1到n中1出现的次数
     * @param n n
     * @return 从1 到 n 中1出现的次数
     * 大佬的解法:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/
     */
    public int NumberOf1Between1AndN_Solution(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+=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;

    }
全部评论

相关推荐

Dream_coding:你是不是只投大厂了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务