标签:log div com tps 位置 需要 产生 practice 分割
题目:
整数中1出现的次数(从1到n整数中1出现的次数)
链接:
https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?tpId=13&tqId=11184&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目描述:
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。
思路:
代码:
1 class Solution { 2 public: 3 int NumberOf1Between1AndN_Solution(int n) 4 { 5 int count = 0; 6 long long i =1; 7 for(i =1;i<=n;i*=10) 8 { 9 // i 表示当前分析的是哪一个数位 10 int a =n/i, b = n%i; 11 count = count +(a+8)/10*i+(a%10 == 1)* (b+1); 12 } 13 return count; 14 } 15 };
剑指offer之【整数中1出现的次数(从1到n整数中1出现的次数)】
标签:log div com tps 位置 需要 产生 practice 分割
原文地址:http://www.cnblogs.com/wangshujing/p/6941438.html