题目:
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]
链接:https://leetcode.com/problems/fizz-buzz/#/description
3/22/2017
1 public class Solution { 2 public List<String> fizzBuzz(int n) { 3 List<String> ret = new LinkedList<String>(); 4 5 for(int i = 1; i <= n; i++) { 6 if (i % 3 != 0 && i % 5 != 0) { 7 ret.add(Integer.toString(i)); 8 } else { 9 StringBuilder sb = new StringBuilder(); 10 if (i % 3 == 0) sb.append("Fizz"); 11 if (i % 5 == 0) sb.append("Buzz"); 12 ret.add(sb.toString()); 13 } 14 } 15 return ret; 16 } 17 }
看到别人不用%的方法
1 public class Solution { 2 public List<String> fizzBuzz(int n) { 3 List<String> ret = new ArrayList<String>(n); 4 for(int i=1,fizz=0,buzz=0;i<=n ;i++){ 5 fizz++; 6 buzz++; 7 if(fizz==3 && buzz==5){ 8 ret.add("FizzBuzz"); 9 fizz=0; 10 buzz=0; 11 }else if(fizz==3){ 12 ret.add("Fizz"); 13 fizz=0; 14 }else if(buzz==5){ 15 ret.add("Buzz"); 16 buzz=0; 17 }else{ 18 ret.add(String.valueOf(i)); 19 } 20 } 21 return ret; 22 } 23 }
纪念一下,这是我3年前找现在工作时电话面试题,当年leetcode题非常少,我做了十几道最多不过三十道就找到工作了。如今水涨船高,欠下的账在慢慢补。