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

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;
	

}
posted @ 2017-05-05 12:08  wdan2016  阅读(826)  评论(0编辑  收藏  举报