LeetCode 233.Number of Digit One

  • 题目描述
    Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
    Example:
    Input: 13
    Output: 6
    Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

  • 思路分析

  1. 暴力法:对10求余,判断个位是否为1,然后除10依次判断//会超时
  2. 优化:总结n每位数的规律,以n=123为例(1的个数:count; 当前位数上的权重:weight;
    当前位数上的数字:now; 上一位数:last,例如按照从右到左,2的上一位数为3;循环次数:round)
    个位数:3属于大于等于1,第十三个循环开始,则count = round + 1 = 12 + 1;
    若为120,即now为小于1,开始第十三个循环,则count = round = 12;
    十位数及以上位数:以十位数为例,2大于1,则count = round*weight + weight=1 * 10+10
    若为11X,即now为1,则count = round * weight + 1+last=1 * 10 + 1 + x
    若为10X,即now等于0,则count=round * weight=1 * 10
  • 代码
 class Solution {
    public int countDigitOne(int n) {
        if(n<1){
            return 0;
        }
        int count = 0;
        int round = n;
        int weight =1;
        int now = 0;
        while(round>0){
        	now = round%10;
        	round = round/10;
        	if(now == 1){
        		count = count + (n%weight) + 1;
        	}
        	else if(now >1){
        		count =count +weight;
        	}
        	count = count + round*weigght;
        	weight = weight*10;
        }
        return count;
    }
 }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值