转载:Java developer group的一个面试题

2014-05-14 06:30:01 阅读( 4 )

2268人 收藏本页

标签:Java面试题

题目:Write a program that prints the numbers from 1 to 100. But for multiples of three print ‘Fuzz’ instead of the number and for the multiples of five print ‘Bizz’ For numbers which are multiples of both three and five print ‘FuzzBizz’.

Let’s see how your code looks like:

METHOD 1 (basically the same as Abhishek’s method)
——————————————————————————–

for (String s = null, int n = 1; n <= 100; n++) {

s = (n%15 == 0) ? “FuzzBizz” : (n%3 == 0) ? “Fuzz” : (n%5 == 0) ? “Bizz” : Integer.toString(n);

System.out.println(s);
}

METHOD 2 (my favourite):
————————————–

for (String s = null, int n = 1; n <= 100; n++) {

s = (n%3 != 0 && n%5 != 0) ? Integer.toString(n) : (n%5 != 0) ? “Fuzz” : (n%3 != 0) ? “Bizz” : “FuzzBizz”;

System.out.println(s);
}

METHOD 3: Somay’s method

METHOD 4:
——————

private static String[] s = new String[15];

static {
s[0] = “FuzzBizz”;
s[3] = s[6] = s[9] = s[12] = “Fuzz”;
s[5] = s[10] = “Bizz”;
}

public static void main(String[] args) {
for(int i = 1; i <= 100; i++) {

if (s[i%15] != null) {

System.out.println(s[i%15]);

} else {

System.out.println(i);

}

}
}

来自IT公司面试手册

下一篇:高级Java程序员面试要点

上一篇:What is Synchronized block and Synchronized Method? and Why we need those

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题