233. Number of Digit One

来源:互联网 发布:plc编程软件win7 64位 编辑:程序博客网 时间:2024/06/13 09:39

problem:

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

solution:

int countDigitOne(int n) {    int ones = 0;    for (long long m = 1; m <= n; m *= 10) {        int a = n/m, b = n%m;        ones += (a + 8) / 10 * m + (a % 10 == 1) * (b + 1);    }    return ones;}
这道题是看了答案之后做出来的,开始的时候我想的是将数分割,但是这样的话比较复杂,需要先找出最大的一位数,并进行是否为1的讨论,再根据最大位数找到其中1的个数,在进行递推,找到个位数为止,例如1234,分为1000+200+30+4,1000中有300(100+10*20)个1,然后1234%1000=234,所以千位数中出现了535(300+234+1)个1,200中有140(100+20*2)个1,30中有13(10+1*3)个1,4中有1个1,加起来和就是689个。

答案的做法先算个位数,然后到最高位数,所以不用先求得最大位置,简便了算法,具体讲解看链接https://leetcode.com/problems/number-of-digit-one/discuss/

原创粉丝点击