簡單的 FizzBuzz 藏有 深度(google 面試題)

Bear熊
6 min readApr 18, 2017

[心得] 學界轉業界…google面試洗臉心得

Re: [心得] 學界轉業界…google面試洗臉心得

看到這兩篇文章,其中第一篇還有leetcode的其他題沒看,不過之前因為做過FizzBuzz 所以特別有共鳴!因為這題算是一個簡單的題目,但是看似簡單的題目好像背後的意義並不簡單。

# 版本一

for(int i = 1; i<= n; i++){
if(i%15 == 0){
System.out.println("FizzBuzz");
continue;
}
if(i%3 == 0){
System.out.println("Fizz");
continue;
}
if(i%5 == 0){
System.out.println("Buzz");
continue;
}
System.out.println(i);
}

# 版本二

for(int i = 1; i <= n; i++){
String result = "";
if(i%3 == 0) result += "Fizz";
if(i%5 == 0) result += "Buzz";
if(result.length() > 0)
System.out.println(result);
else
System.out.println(i);
}

# 版本三

for(int i = 1; i<= n; i++){
if(i%15 == 0){
System.out.println("FizzBuzz");
} else if(i%3 == 0){
System.out.println("Fizz");
} else if(i%5 == 0){
System.out.println("Buzz");
} else {
System.out.println(i);
}
}

最後,最好的答案是第二種

節錄自第二篇文章中一位大大講的話

今天這問題的核心不就是全條件完才知道結果是啥?

3的倍數印Fizz、5的倍數印Buzz,這兩個條件是獨立的

如果同時滿足兩個條件,自然兩個都做,只有版本二滿足這原

則,版本一三都是hardcode 15的倍數這個沒必要的條件

如果條件多7倍數印Woof,不就要再i%105、i%21、i%35、i%7?

但是版本二就是加一行而已

另外在第一篇中有一位大大推的文章我覺得很實用

When doing a whiteboard coding interview and you get stuck, is it okay to explain to the interviewer how you’d use Google to find an answer?

大意是說白板coding其實本意(最好不要是)不是考一些你已經會的東西,而是考一個你可能不會的問題,然後你要keep trying, keep doing下去,因為它的本質是在考一個未來你可能碰到的問題(而且可能google不到),

Yes, I’m sure that you could google a solution to this problem. I’m not asking you this question because I’m thinking 「Gee, you might need to solve this exact question in real life. If that happened, could you do it?」 I’m asking because I believe that solving this question gives me an idea of how effectively your brain can solve problems. Your ability to Google the answer is irrelevant.

最後一段提到

This is what a good interviewer should do because whiteboard coding is about brain power not Google power. If you have a bad interviewer, well, all bets are off.

共勉之

2018/10/20 更新

let fizzBuzz = function(n) {
let result = [];

let mappings = {
3: 'Fizz',
5: 'Buzz'
};
for (let i = 1; i <= n; i++) {
let str = '';

for (let key in mappings) {
if (i % parseInt(key, 10) === 0) {
str += mappings[key];
}
}

if (!str) {
str += i;
}

result.push(str);
}

return result;
};

有第三種解法 更 function 只要接受 Input 完全不用改動程式碼

2020/08/10更新

有提到CPU 其實做 加減乘 很快 但是做除不快(或是%)

所以改用加法

vector<string> fizzBuzz(int n) { //C++
vector<string> res(n);
for(int i = 1;i <= n; i++) {
res[i - 1] = to_string(i);
}
for(int i = 2;i < n; i += 3) {
res[i] = "Fizz";
}
for(int i = 4;i < n; i += 5) {
res[i] = "Buzz";
}
for(int i = 14;i < n; i += 15) {
res[i] = "FizzBuzz";
}
return res;
}

或這種

public List<String> fizzBuzz(int n) {
List<String> ret = new ArrayList<String>(n);
for(int i=1,fizz=0,buzz=0;i<=n ;i++){
fizz++;
buzz++;
if(fizz==3 && buzz==5){
ret.add("FizzBuzz");
fizz=0;
buzz=0;
}else if(fizz==3){
ret.add("Fizz");
fizz=0;
}else if(buzz==5){
ret.add("Buzz");
buzz=0;
}else{
ret.add(String.valueOf(i));
}
}
return ret;
}

--

--