Fizz Buzz
题目:
Given number n. Print number from 1 to n. But:
when number is divided by 3, print "fizz".
when number is divided by 5, print "buzz".
when number is divided by both 3 and 5, print "fizz buzz".
分析:
两种int转string的方法
res.add(Integer.toString(i) );
res.add(String.valueOf(i) );
解法:
class Solution {
/**
* param n: As description.
* return: A list of strings.
*/
public ArrayList<String> fizzBuzz(int n) {
ArrayList<String> res = new ArrayList<String>();
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
res.add("fizz buzz");
} else if (i % 3 == 0) {
res.add("fizz");
} else if (i % 5 == 0) {
res.add("buzz");
} else {
// res.add(Integer.toString(i) );
res.add(String.valueOf(i) );
}
}
return res;
}
}