现在的位置: 首页 > 综合 > 正文

统计从1到n整数中1出现的次数

2017年10月28日 ⁄ 综合 ⁄ 共 968字 ⁄ 字号 评论关闭

思想:按照位数分别进行统计,设数字为num,位数为counter

个位:counter = num/10+n(个位为0,n=0;个位为1,n=1;个位>1,n=1)

十位:counter = num/100*10+n(十位为0,n=0;十位为1,n=低1位+1;十位>1,n=10)

百位:counter = num/1000*100+n(百位为0,n=0;百位为1,n=低2位+1;百位>1,n=100)

。。。。。。

算法描述:

a.求出num的位数figure

b.counter += num/10^i*10^(i-1),1<=i<=figure

c.余数remainder = num/10^(i-1)%10,如果remainder
= 1,counter+= num%10^(i-1)+1;如果remainder > 1,counter += 10^(i-1);remainder
= 0不做处理,1<=i<=figure。

/**
	 * @author PLA 
	 * 统计从1到n整数中1出现的次数
	 */
	public static void main(String[] args) {
		int num = 125;
		count(num);
	}
	public static void count(int num){
		int figure = 0;
		int temp = num;
		int counter = 0;//计数器
		int remainder = 0;//余数
		while(temp!=0){//统计数字位数
			temp = temp/10;
			figure++;
		}
		for(int i=1;i<=figure;i++){//从个位数开始统计
			counter+=num/amount(i)*amount(i-1);
			remainder = num/amount(i-1)%10;
			if(remainder == 1){
				counter+=num%amount(i-1)+1;
			}
			if(remainder > 1){
				counter+=amount(i-1);
			}
			}
		System.out.println(num+"含1的个数为:"+counter+"个");
	}
	private static int amount(int i) {
		// TODO Auto-generated method stub
		int n = 1;
		if(i==0)
			return 1;
		for(int j=0;j<i;j++){
			n*=10;
		}
		return n;
	}

抱歉!评论已关闭.