编程之美2.4 求1的个数

推荐http://blog.csdn.net/zhanglei0107/article/details/8232099

从1到n的所有数中,1出现的次数 例如:f(2)=1,因为就有一个1,f(13)=6,有1,10,11,12,13,1一共出现6次


#include <iostream>
#include <string>
using namespace std;
void fun(int n){
	int icur = 0;
	int ihigh = 0;
	int ilower = 0;
	int icount = 0;
	int ifactor = 1;
	while(n/ifactor!=0){
		ilower = n-n/ifactor*ifactor;
		icur = n/ifactor%10;
		ihigh = n/(ifactor*10);
		switch(icur){
		case 0:
			icount+=ihigh*ifactor;
			break;
		case 1:
			icount+=ihigh*ifactor+ilower+1;
			break;
		default:
			icount+=(ihigh+1)*ifactor;
			break;
		}
		ifactor*=10;
	}
	cout<<icount<<endl;
}
int main(){
	fun(2517);
	return 0;
}

2、扩展问题

同之前问题1的分析,二进制数1101十位为0,十位出现1的有11,10,111,110,1011,1010

推理若某位为0,则该位出现1的次数由高位数字(11)*当前位数(10即2^1)决定

二进制数1111十位为1,十位出现1的有11,10,111,110,1011,1010,1110,1111

推理若某位为1,则该位出现1的次数由高位数字(11)*当前位数(10即2^1)加上低位数字+1决定

#include<iostream>

using namespace std;
int NumOfOne(int n){
	int iLowerNum=0;
	int iCurrNum=0;
	int iHigherNum=0;
	int iFactor=1;
	int iCount=0;
	while(n/iFactor!=0)
	{
		iLowerNum=n-n/iFactor*iFactor;
		iCurrNum=n/iFactor%2;
		iHigherNum=n/(iFactor*2);
		if(iCurrNum==0)
			iCount=iHigherNum*iFactor;
		else
			iCount=iHigherNum*iFactor+iLowerNum+1;
		iFactor*=2;
	}
	return iCount;


}

int main(){
	cout<<NumOfOne(13)<<endl;
	cout<<NumOfOne(15);
	system("pause");
	return 0;

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值