博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1的数目(编程之美2.4)

Posted on 2010-09-23 15:59  KurtWang  阅读(489)  评论(0编辑  收藏  举报
// 2_4.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


long sum1s(long n)
{
	long count =0;
	long factor = 1;

	long lower = 0;
	long cur = 0;
	long higher = 0;

	while(n/factor != 0)
	{
		lower = n - (n/factor)*factor;
		cur = (n/factor)%10;
		higher = n/(factor*10);

		switch(cur)
		{
		case 0:
			count += higher * factor;
			break;
		case 1:
			count += higher * factor + lower + 1;
			break;
		default:
			count+= (higher +1) * factor;
		}
		factor *= 10;
	}
	return count;
}

int _tmain(int argc, _TCHAR* argv[])
{
	printf("%ld\n", sum1s(93));
	return 0;
}