Lintcode9-Fizz Buzz-Easy
2024-10-21 06:35:21
Fizz Buzz
Given number n. Print number from 1 to n. But:
- when number is divided by
3
, print"fizz"
. - when number is divided by
5
, print"buzz"
. - when number is divided by both
3
and5
, print"fizz buzz"
. - when number can't be divided by either
3
or5
, print the numberitself
.
Example
If n = 15, you should return:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]
If n = 10, you should return:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz"
]
Challenge
Can you do it with only one if
statement?
注意:
- 同时被3和5整除,应该是 num % 15 == 0 , 而不是 nums % 3 == 0 && nums % 5 == 0 , 后者会加长运行时间。
- 四种情况的判断顺序很重要,同样影响运行时间。采用 "if - else if - else if - else": if (num % 15 == 0)- else if (num % 5 == 0) - else if (num % 3 == 0) - else. else if 对判断先后顺序有要求,不可颠倒。而如果全部是if, 每个if判断的条件会增加,即增加运行时间。if (num % 15 == 0)- if (num % 5 == 0 && num % 3 != 0) -if (num % 3 == 0 && num % 5 != 0) - else.
- Java int -> String : String s = String.valueOf(i);
- List.add() 参数只能是字符串,所以 line 13.
代码:
public List<String> fizzBuzz(int n) {
int num = 1;
List<String> fblist = new ArrayList<String>(); while (num <= n){
if (num % 15 == 0) {
fblist.add("fizz buzz");
} else if (num % 5 == 0) {
fblist.add("buzz");
} else if (num % 3 == 0) {
fblist.add("fizz");
} else {
fblist.add(String.valueOf(num));
}
num++;
}
return fblist;
}
最新文章
- python学习道路(day10note)(线程,进程)
- sqlalchemy中文乱码问题解决方案
- Droidicon – 1600+ 漂亮的 Android 图标
- 阿里云 CentOS6.5 ssh连接慢的解决方案
- 锁ReaderWriterLockSlim介绍
- Python Django 开发 3 数据库CURD
- Qt的学习资料比起其它C/C++的GUI组件来说已经算很全的了
- STM32F0xx_USART收发配置详细过程
- Android - Facebook KeyHash 設定
- 动态加载下拉框列表并添加onclick事件
- [小知识点]IE6下不支持:hover的解决方法
- ural 1100. Final Standings(数据结构)
- Java经典编程题50道之五
- STL:vector容器用法详解
- mysql常见安全加固策略
- FreeMarker生成Word文档
- TFC2017 腾讯Web前端大会参会小结
- webservice之wsdl
- All the Apache Streaming Projects: An Exploratory Guide
- Web Service测试工具小汇