剑指offer-整数中1出现的次数

来源:互联网 发布:08cms 编辑:程序博客网 时间:2024/04/29 11:51

计算题,纯手算找规律。

int NumberOf1Between1AndN_Solution(int n){    int m = n;    int length = 0;    int num = 0;    int sum = 0;    if(n==0) return 0;    if (n < 10) return 1;    while (m > 0)    {        m /= 10;        length++;    }    length++;    vector<int> table,table_sum;    table_sum.push_back(0);table_sum.push_back(1);    table.push_back(0); table.push_back(1);    for (int i = 2; i < length; i++)    {        table.push_back(table_sum[i - 1] * 9 + pow(10, i - 1));        table_sum.push_back(table[i] + table_sum[i - 1]);    }    length--;    for (int i = 1; i < length; i++)    {        int base = pow(10, length - i);        int times = n / base;        num = times*base;        if (times == 1)         {            sum += table_sum[length - i] + 1+ n%base;        }        else sum += pow(10, length - i) + times*table_sum[length - i];        n = n%base;        if (n == 0) break;    }    if (n % 10 > 1) sum++;    return sum;}
0 0
原创粉丝点击