ZJU PAT 1049 Counting Ones

给定正整数n<2^30,求出从0到n所有整数中1的个数。傻傻地一个个去数肯定是不行的,这种方法去哪里面试人家都不会要你。关键在于找到数字每一位上出现1的规律。这题好像编程之美上有讲,具体就不详述了。比较讨厌的是pat限制的运行时间是80ms,用python写无论如何都是运行超时,翻译成c++的代码就直接ac了

 

 1 d = input()
 2 x = 1
 3 total = 0
 4 while d/x != 0:
 5     right = d%x
 6     left = d/(x*10)
 7     current = (d/x)%10
 8     if current == 0:
 9         total += left * x
10     elif current == 1:
11         total += left * x + right + 1
12     else:
13         total += (left+1)*x       
14     x = x * 10
15 print total

 

posted @ 2013-01-21 16:36  S.Zhang  阅读(1206)  评论(0编辑  收藏  举报