一道淘汰85%面试者的百度开发者面试题

来源:互联网 发布:小受坐轮椅卖淘宝 编辑:程序博客网 时间:2024/05/22 23:37

依序遍历0到100闭区间内所有的正整数,如果该数字能被3整除,则输出该数字及‘*’标记;如果该数字能被5整除,则输出该数字及‘#’标记;如果该数字既能被3整除又能被5整除,则输出该数字及‘*#’标记。

链接地址

直接给代码吧,数学这块,真没啥说的。

public class ArrayBaidu {public static void main(String[] args) {long now = System.currentTimeMillis();ArrayBaidu arrBai = new ArrayBaidu();String ins = arrBai.outArr();System.out.println(ins);// arrBai.foo();// arrBai.who();long end = System.currentTimeMillis();System.out.println(end - now);}public String outArr() {StringBuffer buf = new StringBuffer();// 将100按15分段for (int i = 0; i <= 10000; i += 15) {// 隔15一次循环,格式类似for (int j = i; j < i + 15; j += 3) {switch ((j % 15) / 3) {case 0:buf.append(j + "*#" + (j + 1) + (j + 2));continue;case 1:buf.append(j + "*" + (j + 1) + (j + 2) + "#");continue;case 2:buf.append(j + "*" + (j + 1) + (j + 2));continue;case 3:buf.append(j + "*" + (j + 1) + "#" + (j + 2));continue;case 4:buf.append(j + "*" + (j + 1) + (j + 2));continue;default:break;}}}// 分割字符串,后面有超出100的数字String ins = buf.toString();ins = ins.split("10001")[0];return ins;}/** * 楼主给的错误代码 */public void foo() {for (int i = 0; i < 10000; i++) {if (i % 3 == 0) {System.out.println(i + " *");} else if (i % 5 == 0) {System.out.println(i + " #");} else if (i % 3 == 0 && i % 5 == 0) {System.out.println(i + " *#");}}}/** * 其他的,看了下大部分都是这样写的,随便找了个 */public void who() {for (int i = 0; i <= 10000; i++) {String result = "";if (i % 3 == 0) {result += i + "*";if (i % 5 == 0) {result += "#";}System.out.println(result);} else if (i % 5 == 0) {result += i + "#";System.out.println(result);}}}}

运行:
outarr():

foo():

who():


说明:

       1.当数值很大的时候,长字符串的操作就会很费时间,所以那时就不要拼接了。


0 0
原创粉丝点击