剑指offer 32. 1到n整数中2出现的次数

//题目:从1到n个整数中输出2出现的次数
//解法1:同一每个数字中包含2的次数并相加
public class Main {

	public static void main(String[] args) throws Exception {
		System.out.println(get2Count(100));
	}

	public static int get2Count(int n){
		int i = 1;
		int result = 0;
		while(i<=n){
			result = result+getNum(i);
			i++;
		}
		return result;
	}
	
	public static int getNum(int num){
		int result = 0;
		while(num != 0){
			if(num%10 == 2){
				result++;
			}
			num = num/10;
		}
		return result;
	}
	
}

//解法2:按照数字位数出现的次数进行计算
public class Main {
	
	public static void main(String[] args) throws Exception {
		System.out.println(get2Count(100));
	}
	
	public static int get2Count(int n){
		String str = String.valueOf(n);
		return getNum(str);
	}
	
	public static int getNum(String str){
		if(str == null || str.length() == 0){
			return 0;
		}
		int length = str.length();
		int first = str.charAt(0)-'0';
		if(length == 1 && first>1){
			return 1;
		}
		if(length == 1 && first<=1){
			return 0;
		}
		int numFirst = 0;															//第一位可能出现2的次数和两种可能
		if(first>2){															
			numFirst = (int)Math.pow(10,length-1);
		}else if(first == 2){
			numFirst = Integer.parseInt(str.substring(1))+1;
		}
		int numSecond = first*(length-1)*(int)Math.pow(10,length-2);				//剩余位在第一位不变的情况下可能出现2的次数,其实就是全排列
		int numIter = getNum(str.substring(1));										//将第一位删除,迭代执行程序
		return numFirst+numSecond+numIter;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值