从1到n整数中1出现的次数--简短解法

剑指offer中给出了解题的思路,但程序略嫌繁琐,它先将整数转化成字符串之后进行操作,本文给出了一个相对简洁程序。

具体思路如下:

(123456)的1个数  =  23456+1 + 5*pow(10,5-1) + (23456)的1个数

 (23456)的1个数   =    3456+1 + 4*pow(10,4-1) + (3456)的1个数

。。。

代码如下:

#include<iostream>
using namespace std;
int count1number(unsigned N){
	int k=0;  //N的总位数-1
	int tmp=1;//10**(k-1)
	while(N>=tmp*10){
		tmp*=10;
		k++;
	}
	int count =0;
	while(tmp>=1){
		if((N/tmp)%10!=0){
			if(N/tmp==1)
				count +=N%tmp+1+N/tmp*k*(tmp/10);
			else 
				count +=tmp+N/tmp*k*(tmp/10);
		}
		N%=tmp;
		tmp/=10;
		k--;
	}
	return count;
}

int count1BF(unsigned N){
	int tmp=1;
	int count=0;
	while(N/tmp){
		if((N/tmp)%10==1)
			count++;
		tmp*=10;
	}
	return count;
}
int main(){
	int N=100;
	for(N=0;N<101;++N){
		int count =0;
		for(int i=1;i<=N;i++){
			count+=count1BF(i);
		}
		int count2=count1number(N);
		cout<<"N:"<<N<<" "<<count<<" "<<count2<<endl;
	}

	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值