1049. Counting Ones (30) 从1到n整数中1出现的次数

剑指offer,leetcode,PAT

转载地址(下面的博文讲解的很清楚,容易明白)
http://blog.csdn.net/yi_afly/article/details/52012593

这里写图片描述

PAT题目联系
https://www.patest.cn/contests/pat-a-practise/1049
ac代码

#include <cstdio>
#include <memory>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <sstream>
#include <list>
#include <stack> 
#include <map> 
#include <set> 

using namespace std;

#define INF 0x7fffffff

const int N = 505;

int main()
{
  //freopen("in.txt", "r", stdin);
  int n;
  while(scanf("%d", &n) != EOF)
  {
    if(n<1)
    {
      printf("0\n");
      continue;
    }

    int base = 1;

    int count = 0;

    int round = n;
    while(round > 0) // 依次遍历 每一位的数字
    {
      int weight = round%10; // 当前位的值

      round/=10; // 去除当前位,前面的数字值

      count += round*base;

      /**
       * 比如 514 ,十位是1
            10个数: 010 011 012 ... 019
            10个数: 110 111 112 ... 119
            10个数: 210 211 212 ...
            ...
            10个数: 410 411 ...
            5个数: 510 511 512 513 514, 最后一轮需要看个位数是多少了
       */
      if(weight == 1) // 当前位的值就是1,需要看当前位后面的数是多少
      {  
        count += (n%base) + 1;
      }
      else if(weight > 1) // 当前位值大于1 那么最后一轮还是base个数
      {
        count += base;
      }

      base*=10;
    }

    printf("%d\n", count);
  }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值