编程之美 2.4

输出1-N中包含1的数目:

import java.util.*;
public class Main{
    public static void main(String[] args) {
        int n=93;
        int factor=1;
        int res=0;
        while(n/factor!=0){
            int lowerNum=n-(n/factor)*factor;
            int curNum=(n/factor)%10;
            int highNum=n/(factor*10);
            if(curNum==0){
                res+=highNum*factor;
            }else if(curNum==1){
                res+=highNum*factor+lowerNum+1;
            }else{
                res+=(highNum+1)*factor;
            }
            factor=factor*10;
        }
        System.out.println(res);
    }
}

 

posted @ 2018-04-13 11:38  xinyilovestudy  阅读(114)  评论(0编辑  收藏  举报