統計從1到n整數中1出現的次數

思想:按照位數分別進行統計,設數字爲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;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章