java_day22

目标:Java web开发

问题:求a和b之间的所有数字中0∼9的出现次数

import java.io.*;
import java.util.*;
class Main{
    static int get(List<Integer> list,int l,int r){
        int res=0;
        for(int i=l;i>=r;i--){
            res=res*10+list.get(i);
        }
        return res;
    }
    static int power10(int x){
        int res=1;
        while(x!=0){
            res*=10;
            x--;
        }
        return res;
    }
    static int count(int n,int x){
        if(n==0) return 0;
        List<Integer> list=new ArrayList<Integer>();
        while(n!=0){
            list.add(n%10);
            n/=10;
        }
        int len=list.size();
        int res=0;
        for(int i=len-1-(x==0?1:0);i>=0;i--){//在0到n的所有数中,第i位的x总数
            if(i<len-1){
                res+=get(list,len-1,i+1)*power10(i);//第i位之前
                if(x==0) res-=power10(i);
            }
            if(list.get(i)>x) res+=power10(i);//看第i位之后
            else if(list.get(i)==x) res+=get(list,i-1,0)+1;
        }
        return res;
    }
    public static void main(String[] args) throws IOException{
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        while(true){
            String[] ss=in.readLine().split(" ");
            int a=Integer.parseInt(ss[0]);
            int b=Integer.parseInt(ss[1]);
            if(a==0&&b==0) break;
            if(a>b){
                int tmp=a;
                a=b;
                b=tmp;
            }
            for(int i=0;i<10;i++){
                System.out.print(count(b,i)-count(a-1,i)+" ");
            }
            System.out.println();
        }
    }
}
posted @ 2021-07-30 21:57  zhuangzhongxu  阅读(25)  评论(0)    收藏  举报