count the number of 2s

Write a method to count the number of 2s between 0 and n.

一本书的页码从自然数1 开始顺序编码直到自然数n。书的页码按照通常的习惯编排,每个页码都不含多余的前导数字0。例如,第6 页用数字6 表示,而不是06 或006 等。数字计数问题要求对给定书的总页码n,计算出书的全部页码中分别用到多少次数字0,1, 2,…,9。


下面的代码计算出用到多少次数字2.

public static int count2sR(int n) {
	// base case
	if (n==0) return0;

	// 513 = 5*100 +13;  [power = 100, first = 5, remainder =13]
	int power = 1;
	while(10*power<n)
		power*=10;

	int first = n/power;
	int remainder = n%power;

	// count 2s from the first digit
	int nTwosFirst = 0;
	if(first>2) nTwosFirst+=power;
	else if (first==2) nTwosFirst += remainder+1;

	// count 2s from all other digits
	int nTwosOther = first* count2sR(power-1) + count2sR(remainder);

	return nTwosFirst + nTwosOther;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值