leetcode 233. Number of Digit One

789 ワード

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.
class Solution {
public:
    int countDigitOne(int n) {
		if(n/10==0)
			return n>=1?1:0;
		int num=n;
		int len=0;
		while(num!=0)
		{
			num=num/10;
			len++;
		}
		
		//char str[100];
		//_itoa(n,str,10);
		int k=n/pow(10,len-1);
		//cout<<strlen(str)<<endl;
		if(k==1)
			return pow(10,len-2)*(len-1)+countDigitOne(n-pow(10,len-1))+n-pow(10,len-1)+1;
		else
		return k*(len-1)*pow(10,len-2)+pow(10,len-1)+countDigitOne(n-k*pow(10,len-1));
    }
};

これは主に数学の配列の組み合わせを使って、和を求めて、数学の内容は少し多いです
accepted