233. Number of Digit One
Total Accepted: 13442 Total Submissions: 59263 Difficulty: Medium
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.
举例分析
641中有多少个1?
求func(641)
641分为[0,599]和[600,641]
[0,599]:
固定百位的1有1*10*10种
固定十位的1有6*1*10种
固定个位的1有6*10*1种
[600,641]只需计算0-41中1的个数也就是func(41)
所以func(641) = 1*10*10+6*1*10+6*10*1+func(41);
641是一个三位数,设m=3表示n是一个m位的数
也就是func(641) = pow(10,m-1) +(m-1) * 6 * pow(10,m-2) + func(41)
特殊的,当最高位等于1时有点不一样。例如141
func(141) = 41+1 +(m-1)*1*pow(10,m-2) + func(41)
class Solution { public: int countDigitOne(int n) { if(n<=0) return 0; if(n<10) return 1; string nstr = to_string(n); int m = nstr.size(); int rest = n - (nstr[0]-'0')*pow(10,m-1); int cnt = nstr[0]=='1' ? rest+1: pow(10,m-1); return cnt+(nstr[0]-'0')*(m-1)*pow(10,m-2) + countDigitOne(rest); } };