基础算法练习

来源:互联网 发布:阴阳师录屏软件 编辑:程序博客网 时间:2024/05/20 14:25

题目:随机生成一个从0~10000的数字,如果不足5位,请用0来补上

比如 235 变成00235


我的思路:从左往右取得数字,

如果不为0,就说明我们已经得到了所有的需要补的0的个数,

不然就表示个数的变量自增1


说起来抽象,直接上代码



public static void showN() {Random rand = new Random();int n = rand.nextInt(10000);System.out.println(n);int c;int count = 0;// 算出需要多少0for (int i = 5; i >= 1; i--) {// 从左往右算,看当前位数所在的数是否为0// 不为0的话就跳出,不然就说明当前是0,表示0的常量就++if (n / Math.pow(10, i - 1) % 10 != 0) {// System.out.println(n/c%10+"i/c"+n/c);break;} else {count++;}}// 求出需要的0的个数后,弄上去String result = "";for (int i = 0; i < count; i++) {result += "0";}System.out.println(result + n);}