数字1的数量

来源:互联网 发布:网络舆情5s管理办法 编辑:程序博客网 时间:2024/04/30 13:30
给定一个十进制正整数N,写下从1开始,到N的所有正数,计算出其中出现所有1的个数。
例如:n = 12,包含了5个1。1,10,12共包含3个1,11包含2个1,总共5个1。
Input
输入N(1 <= N <= 10^9)
Output
输出包含1的个数
Input示例
12
Output示例

5

#include <iostream>using namespace std;int fun(int n){    int result = 0;    int left = 0;    int cur = 0;    int right = 0;    int base = 1;        while (n / base > 0)    {        cur = (n / base) % 10;        left = n / (base * 10);        right = n - (n / base) * base;        if (cur == 0)        {            result += (left * base);        }        else if (cur == 1)        {            result += left * base + right + 1;        }        else        {            result += (left + 1) * base;        }                base *= 10;    }        return result;}int main(){    int n;    cin >> n;    cout << fun(n) << endl;    return 0;}


原创粉丝点击