Fizz Buzz
题目地址:
https://leetcode.com/problems/fizz-buzz/description/
题目:
解题思路:
这道题就是用一个指针来做。
代码:
Follow up:
if we cannot use % or /: we can use idea similar to dp.
https://leetcode.com/problems/fizz-buzz/description/
题目:
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"
]
解题思路:
这道题就是用一个指针来做。
代码:
public List<String> fizzBuzz(int n) { List<String> rst = new ArrayList<>(); int i = 1; if(n == 0){ return rst; } while(i <= n){ if(i % 15 == 0){ rst.add("FizzBuzz"); } else if(i % 3 == 0){ rst.add("Fizz"); } else if(i % 5 == 0){ rst.add("Buzz"); } else{ rst.add(String.valueOf(i)); } i++; } return rst; }
if we cannot use % or /: we can use idea similar to dp.
public List<String> fizzBuzz(int n) { List<String> rst = new ArrayList<>(); int i = 0; while(i <= n - 1){ if(i == 14 || (i > 15 && rst.get(i - 15).equals("FizzBuzz"))){ rst.add("FizzBuzz"); } else if(i == 2 || (i > 3 && (rst.get(i - 3).equals("Fizz") || rst.get(i - 3).equals("FizzBuzz")))){ rst.add("Fizz"); } else if(i == 4 || (i > 5 && (rst.get(i - 5).equals("Buzz") || rst.get(i - 5).equals("FizzBuzz")))){ rst.add("Buzz"); } else{ rst.add(String.valueOf(i + 1)); } i++; } return rst; }

Comments
Post a Comment