您的位置:首页 > 其它

求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了,logn的算法复杂度

2017-05-05 12:08 751 查看

include "stdafx.h"

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
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 += round*base;
break;
case 1:
num += round*base + 1 + former;
break;
default:
num += round*base + base;
break;
}

former = current*base+former;
base = base * 10;
n = n / 10;
current = n % 10;
round= n /10;
}
//当round==0时,
switch (current)
{
case 0:
num += round*base;
break;
case 1:
num += round*base + 1 + former;
break;
default:
num += round*base + base;
break;
}
return num;
}
};
int main()
{
Solution so;
cout << so.NumberOf1Between1AndN_Solution(21345) << endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐