编程之美-2.4 1的数目

package code.beauty.fungame;

public class CountOne {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n =1111111110;
//		count1InAllInt(n);
		Sum1s(n);
	}
	private static int count1InAInt(int n){
		int num = 0;
		while(n!=0){
			num += (n%10 == 1)? 1:0;
			n=n/10;
		}
		return num;
	}
	private static void count1InAllInt(int n){
		int num = 0;
		for(int i = 1; i<=n ; i++ ){
			num += count1InAInt(i);
		}
		System.out.println("count1InAllInt:"+num);
	}
	
	private static int Sum1s(int n){
		int sum = 0;
		int iFactor = 1;
		int i_hight = 0;
		int i_low = 0;
		int i_Curr = 0;
		while(n/iFactor!=0){
			
			i_hight = n/(iFactor*10);
			i_low = n%iFactor;
			i_Curr = (n/iFactor)%10;
			switch(i_Curr){
			case 0 :
				sum +=(i_hight*iFactor);
				break;
			case 1 :
				sum +=(i_hight*iFactor + i_low+1);
				break;
			default :
				sum +=((i_hight+1)*iFactor);
			}
			iFactor *=10; 
		}
		System.out.println("Sum1s:"+sum);
		return sum;
	}

}

你可能感兴趣的:(编程之美)