从1到n之间的数字1出现的次数

给定一个数N,求出1-N之间的数字有多少个1,例如N=11时结果为4(只有1,10,11含1)

经典问题。

 

java 实现

package suanfa;

public class FindNumber {

	public static int countNumber(int n){
		int factor=1;
		int cur=0;
		int high=0;
		int low=0;
		int count=0;
		while(n/factor>0){
			low=n%factor;
			cur=n/factor%10;
			high=n/factor/10;
			if(cur==0){
				count+=high*factor;
			}
			else if(cur==1){
				count+=high*factor+low+1;
			}
			else {
				count+=(high+1)*factor;
			}
            factor*=10;
            
		}
		return count;
	}
	public static void main(String[] args) {
		
		System.out.println("result is "+countNumber(11));
		
	}
}

 

你可能感兴趣的:(1-N之间数字)