pat 1049 Counting Ones

第4,6个点超时。后来发现居然是编程之美的一道原题,用了书上代码,直接AC。

代码:

 

//1049 20:14-20:35
#include<stdio.h>
const int NUM=100000000;
int find(int x)
{
	int res=0;
	while(x){
		if(x%10==1)
			res++;
		x=x/10;
	}
	return res;
}

int find1(int x)
{

}
int a[NUM];

int main()
{
	int i,j,n;
	scanf("%d",&n);
	a[0]=0;
	for(i=1;i<=n;i++){
		a[i]=a[i-1]+find(i);

	}
	printf("%d",a[n]);
	return 0;
}

AC代码:

//1049 22:31
#include<stdio.h>
int main()
{
	int n;
	int iCount=0;
	int iFactor=1;
	int iLowerNum=0;
	int iCurrNum=0;
	int iHigherNum=0;
	scanf("%d",&n);
	while(n/iFactor!=0)
	{
		iLowerNum = n -(n/iFactor) *iFactor;
		iCurrNum = (n/iFactor)%10;
		iHigherNum = n/(iFactor *10);

		switch(iCurrNum){
		case 0:
			iCount+=iHigherNum * iFactor;
			break;
		case 1:
			iCount +=iHigherNum*iFactor + iLowerNum +1;
			break;
		default:
			iCount +=(iHigherNum+1) *iFactor;
			break;
		}
		iFactor*=10;
	}
	printf("%d",iCount);
	return 0;
}



你可能感兴趣的:(pat 1049 Counting Ones)