1的数目

1.暴力O(nlogk)
class Solution {
public:
    int CountNum(int i)
    {
        int sum=0;
        while(i)
        {
            if(i%10==1)
                sum++;
                i/=10;
        }
        return sum;
    }
    int NumberOf1Between1AndN_Solution(int n)
    {
        int count=0;
        for(int i=1;i<=n;i++)
        {
            count+=CountNum(i);
        }
        return  count;
    }
};

2.参考编程之美 O(logn)
class Solution {  
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int iCount = 0;
        int iFactor = 1;
        int low, curr, high;
        while (n / iFactor)
        {
            low = n - (n / iFactor)*iFactor;
            curr = (n / iFactor) % 10;
            high = n/(iFactor*10);
            switch (curr)
            {
            case 0:
                iCount += high*iFactor;
                break;
            case 1:
                iCount += high*iFactor + low + 1;
                break;
            default:
                iCount += (high + 1)*iFactor;
                break;
            }
                iFactor *= 10;
        }
        return iCount;
    }
};

3.参考剑指offer O(logn)
class Solution {  
public:
	int Power10(int n)
	{
		int result=1;
		for (int i = 0; i < n; i++)
		{
			result *= 10;
		}
		return  result;
	}
	int NumberOf1Between1AndN_Solution(int n)
	{
		char strN[50]="";
        sprintf(strN, "%d", n);
        //_itoa_s(n,strN,50,10);//等价上一句vs2013AC,牛客不行
		if (!strN || *strN == '\0' || *strN<='0' || *strN>'9')
			return 0;
		int len = strlen(strN);
		/*就以21345为例,先分为两段0-1345,1346-21345,*/
		
		//首位2、  10000-19999
		int SecDfirstnum=0,Othernum=0,FistDnum=0;
		
		int first = *strN-'0';
		if (1 == first)
		{
			SecDfirstnum = atoi(strN+1)+1;
		}
		else
		{
			SecDfirstnum = Power10(len-1);
		}
		//首位2后面四位
		Othernum = first*(len - 1)*Power10(len - 2);
		//第一段
		int m = atoi(strN + 1);
		FistDnum = NumberOf1Between1AndN_Solution(m);
			
		return SecDfirstnum + Othernum + FistDnum;
	}
};			
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值