這題主要是解倍數問題,三倍則放 Fizz ,五倍放 Buzz,十五倍放 FizzBuzz,其餘純數字。
LeetCode 題目連結
https://leetcode.com/problems/fizz-buzz/
題目
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" ]
Accept 作法
本題很單純尚無遇到陷阱。Runtime: 5 ms
Memory: 40.7 MB
Java 程式碼
class Solution { public ListfizzBuzz(int n) { List resultList = new ArrayList (); for(int i = 0;i<n;i++){ if((i+1) %15 == 0){ resultList.add(i,"FizzBuzz"); } else if((i+1) %3 == 0){ resultList.add(i,"Fizz"); }else if((i+1) %5 == 0){ resultList.add(i,"Buzz"); }else{ int count = i+1; resultList.add(i,""+count); } } return resultList; } }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言