从1到n整数中1出现的次数

来源:互联网 发布:java kafka 生产者 编辑:程序博客网 时间:2024/04/30 10:30

代码:

#define  _CRT_SECURE_NO_WARNINGS#include <iostream>using namespace std;int PowerBase10(int n){    int result = 1;    for (int i = 0; i < n; i++)    {        result *= 10;    }    return result;}int Count1OccurTimes(const char* strN){    if (strN == nullptr || *strN < '0' || *strN > '9' || *strN == '\0')        return 0;    int first = *strN - '0';    int length = strlen(strN);    if (length == 1 && first == 0)        return 0;    if (length == 1 && first > 0)        return 1;    int num_first_digit = 0;    if (first > 1)        num_first_digit = PowerBase10(length - 1);    else if (first == 1)        num_first_digit = atoi(strN + 1) + 1;    int num_other_digit = first*(length - 1)*PowerBase10(length - 2);    int num_Recursive = Count1OccurTimes(strN + 1);    return num_first_digit + num_other_digit + num_Recursive;}//剑指offer上面的解法int Count1OccurTimesFrom1Ton(int n){    if (n <= 0)        return 0;    //把整数转为字符串    char strN[50];    sprintf(strN, "%d", n);    return Count1OccurTimes(strN);}// 方法取自这篇博客,很赞 http://blog.csdn.net/yi_afly/article/details/52012593int count(int n){    if (n < 1)        return 0;    int count = 0;    int base = 1;    int round = n;    while (round > 0)    {        int weight = round % 10;        round = 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 number = 21345;    cout << "1 出现次数: "<<Count1OccurTimesFrom1Ton(number)<<endl;    cout << "1 出现次数: " << count(number) << endl;    cout << endl;    system("pause");    return 0;}

测试:

这里写图片描述

0 0