Fizz Buzz
Description
Given number n. Print number from 1 to n. According to following rules:
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”.
when number can’t be divided by either 3 or 5, print the number itself.
public class Solution {
/**
* @param n: An integer
* @return: A list of strings.
*/
public List<String> fizzBuzz(int n) {
// write your code here
List<String> result = new ArrayList<String>() ;
for(int i = 1 ; i <= n ; i++){
if(i % 3 == 0 && i % 5 == 0){
result.add("fizz buzz") ;
}else if(i % 3 == 0 && i % 5 != 0){
result.add("fizz") ;
}else if (i % 5 == 0 && i % 3 != 0){
result.add("buzz") ;
}else{
String count = i + "" ;
result.add(count) ;
}
}
return result ;
}
}
这篇文章详细介绍了如何使用Java编写FizzBuzz问题的解决方案,通过代码展示了如何根据数的除法规则打印相应的'fizz', 'buzz'或'fizzbuzz'。适合初学者理解条件语句和字符串操作。
1万+

被折叠的 条评论
为什么被折叠?



