题目:FizzBuzz

从stdin得到数字N(<10^7),然后从打印出从1到N的数字。输出到stdout,假设数字是3的倍数的话就仅仅打印“Buzz”,假设数字是5的倍数的话就仅仅打印“Fizz”,假设数字同一时候是3和5的倍数的话就打印“FizzBuzz”.

比如输入为15时。输出为:

1

2

Fizz

4

Buzz

Fizz

7

8

Fizz

Buzz

11

Fizz

13

14

FizzBuzz

我当时提交的java代码为:

import java.util.*;
public class Solution {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner in = new Scanner(System.in);
int n = in.nextInt();

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);
}
}
}
}

近期写scala比較多,看着if,else if非常闹心,于是过后又改了一个更简洁的版本号:

import java.io.*;
import java.util.*;

public class CodingProblem2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();

for(int i = 1; i <= n; i++) {
String output = "";
if (i % 3 == 0) output = "Fizz";
if (i % 5 == 0) output += "Buzz";
if (output == "") output = Integer.toString(i);
System.out.println(output);
}
}
}