Love丶FFC's Blog
给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:
规则1.如果这个数被3整除,打印fizz
.
规则2.如果这个数被5整除,打印buzz
.
规则3.如果这个数能同时被3
和5
整除,打印fizz buzz
.
规则4.如果这个数既不能被 3
整除也不能被 5
整除,打印数字本身。
比如 n = 15
, 返回一个字符串数组:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]
你是否可以只用一个 if
来实现
1.共4种情况需要判断,为了达成挑战,需要考虑怎么使用唯一的一个if。
2.使用条件表达式a?b:c可以实现。
3.首先使用if判断该数能否被3整除,然后在if中使用条件表达式,判断该数是否能被5整除,如能5整除,则仅满足规则3,若不能被5整除,则仅满足规则1。然后使用else(该数不能被3整除),判断该数能否被5整除,如能被5整除,则仅满足规则2,如不能被5整除,则仅满足规则4。
package LintCode_Easy; import java.util.ArrayList; import java.util.List; public class _9 { public static void main(String[] args) { int n = 15; List<String> s = new ArrayList<String>(); for(int i=1;i<=n;i++) { if(i%3==0) { s.add((i%5==0)?"fizz buzz":"fizz"); } else { s.add((i%5==0)?"buzz":i+""); } } System.out.println(s); } } /* s.add((i%5==0)?"fizz buzz":"fizz")等同为 if(i%5==0) { s.add("fizz buzz"); } else { s.add("fizz"); } */
public class Solution { public List<String> fizzBuzz(int n) { List<String> s = new ArrayList<String>(); for(int i=1;i<=n;i++) { if(i%3==0) { s.add((i%5==0)?"fizz buzz":"fizz"); } else { s.add((i%5==0)?"buzz":i+""); } } return s; } }
fruinly
Metatarsal bones from both Ifngr2 О”EC and control embryos were isolated at gestational day 18 canadian pharmacy cialis 20mg We found no evidence for a step change in prescribing, despite the guideline causing a large and immediate increase in the population appropriate for tamoxifen
engarma
My oncologist wants me to take and I have picked up the meds but so I am so nervous to start because of info I was told and have read about side effects viagra online prescription Allgren RL, Marbury TC, Rahman SN et al
Preliaf
viagra levitra forum 05, but not the 0
LOumpk
I was so weak and in great pain order priligy online uk
Ihwczw
buy fenofibrate online buy tricor 200mg online cheap buy tricor 160mg
Oyeucm
buy zaditor 1 mg generic order tofranil 75mg online cheap tofranil 25mg pill
Vebijy
oral tadalafil 5mg buy tadalafil 10mg online sildenafil overnight shipping usa
Aptaep
acarbose 25mg tablet buy repaglinide 2mg online order fulvicin 250mg without prescription
Khbykx
buy minoxidil solution for sale buy tadalafil 5mg generic buy ed pills cheap