43 wins the Offer-- face questions: the number of occurrences n is an integer from 1 to 1

43 is inscribed: an integer of from 1 to n times appearing in a
subject: a input integer n, the number of times a request appearing from 1 to n represents the n integers in decimal. For example the input 12, comprising a number of integers from 1 to 12, 10, 11 and 12,1 have appeared in a total of 5 times.

Solution:

  • ◈ does not consider time-efficient solution, relied want to get a little difficult Offer
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
int NumberOf1(unsigned int n){
	int number=0;
	while(n){
		if(n%10==1) number++;
		n/=10;
	}
	return number;
}
int NumberOf1Between1AndN(unsigned int n){
	int number=0;
	for(unsigned int i=1;i<=n;i++){
		number+=NumberOf1(i);
	}
	return number;
}
int main() {
	printf("%d\n",NumberOf1Between1AndN(100)); 
	return 0;
}
  • ◈ proceed to significantly improve the efficiency of the solution from the time the law of numbers, let the interviewer refreshing
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<cstring>
#include<cmath>
using namespace std;
int NumberOf1(const char* strN){
	if(!strN || *strN<'0' || *strN>'9' || *strN=='\0') return 0;
	int first=*strN-'0';
	unsigned int length=static_cast<unsigned int>(strlen(strN));
	
	if(length==1 && first==0) return 0;
	if(length==1 && first>1) return 1;
	
	// 假设 strN 是 "21345"
	// numFirstDigit 是数字 10000~19999 的第一位中的数目
	int numFirstDigit=0;
	if(first>1) numFirstDigit=(int)pow(10, length-1);
	else if(first==1) numFirstDigit=atoi(strN+1)+1;
	
	// numOtherDigits 是 1346~21345 除第一位之外的数位中的数目
	int numOtherDigits=first*(length-1)*((int)(pow(10, length-2)));
	
	// numRecursive 是 1~1345 中的数目
	int numRecursive=NumberOf1(strN+1);
	
	return numFirstDigit+numOtherDigits+numRecursive; 
}
int NumberOf1Between1AndN(int n){
	if(n<=0) return 0;
	char strN[50];
	sprintf(strN, "%d", n);
	
	return NumberOf1(strN);
}
int main() {
	printf("%d\n",NumberOf1Between1AndN(21345)); 
	return 0;
}
Published 46 original articles · won praise 47 · views 1407

Guess you like

Origin blog.csdn.net/qq_35340189/article/details/104443814