求从1到n整数中1出现的次数:O(logn)算法

来源:互联网 发布:淘宝自带erp系统 编辑:程序博客网 时间:2024/05/20 13:37

剑指offer上的一题,但是感觉这位兄弟的解法更好

#include<iostream>using namespace std;#define N 2000int cnt(int n){    if (n < 1)    {        return 0;    }    int count = 0;    int base = 1;    int round = n;    while (round > 0)    {        int weight = round % 10;        round /= 10;        count += round * base;        if (weight == 1)        {            count += (n % base) + 1;        }        else if (weight > 1)        {            count += base;        }        base *= 10;    }       return count;}int main(){    int n;    cin >> n;    cout << cnt(n) << endl;    return 0;}
阅读全文
0 0
原创粉丝点击