求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了,logn的算法复杂度
include "stdafx.h"
include
include
include
include
using namespace std;
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
int current= n % 10 ;
int round = n / 10 ;
int former=0;
int num = 0;
int base = 1;
while (round!=0)
{
switch (current)
{
case 0:
num += roundbase;
break;
case 1:
num += roundbase + 1 + former;
break;
default:
num += round*base + base;
break;
}
former = currentbase+former;
base = base * 10;
n = n / 10;
current = n % 10;
round= n /10;
}
//当round==0时,
switch (current)
{
case 0:
num += roundbase;
break;
case 1:
num += roundbase + 1 + former;
break;
default:
num += roundbase + base;
break;
}
return num;
}
};
int main()
{
Solution so;
cout << so.NumberOf1Between1AndN_Solution(21345) << endl;
}

浙公网安备 33010602011771号