首页 > 其他 > 详细

1049. Counting Ones (30)

时间:2015-12-06 11:30:55      阅读:147      评论:0      收藏:0      [点我收藏+]

The task is simple: given any positive integer N, you are supposed to count the total number of 1‘s in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1‘s in 1, 10, 11, and 12.

Input Specification:

Each input file contains one test case which gives the positive N (<=230).

Output Specification:

For each test case, print the number of 1‘s in one line.

Sample Input:
12
Sample Output:
5

 

  1. #include <string>
  2. #include <iostream>
  3. #include <math.h>
  4. using namespace std;
  5. string str;
  6. int GetLeftNum(int a) {
  7. int left = 0;
  8. for (int i = 0; i < a; i++) {
  9. left *= 10;
  10. left += str[i] - ‘0‘;
  11. }
  12. return left;
  13. }
  14. int GetRightNum(int b) {
  15. int right = 0;
  16. for (int i = b+1; i < str.length(); i++) {
  17. right *= 10;
  18. right += str[i] - ‘0‘;
  19. }
  20. return right;
  21. }
  22. int main(void) {
  23. cin >> str;
  24. if (str.length() == 0) {
  25. cout << 1;
  26. return 0;
  27. }
  28. int oneCnt = 0;
  29. int left = 0, right = 0;
  30. for (int i = 0; i < str.length(); i++) {
  31. left = GetLeftNum(i);
  32. right = GetRightNum(i);
  33. if (str[i] - ‘0‘ > 1) {
  34. oneCnt += (left + 1)*pow(10, str.length() - i - 1);
  35. }
  36. else if (str[i] == ‘1‘) {
  37. oneCnt+= (left)*pow(10, str.length() - i - 1)+right+1;
  38. }
  39. else {
  40. oneCnt += (left)*pow(10, str.length() - i - 1);
  41. }
  42. }
  43. cout << oneCnt;
  44. return 0;
  45. }





1049. Counting Ones (30)

原文:http://www.cnblogs.com/zzandliz/p/5023164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!