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 and 5, print "fizz buzz".
  • when number can't be divided by either 3 or 5, print the number itself.

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?

注意:

  1. 同时被3和5整除,应该是 num % 15 == 0 , 而不是 nums % 3 == 0 && nums % 5 == 0 , 后者会加长运行时间。
  2. 四种情况的判断顺序很重要,同样影响运行时间。采用 "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.
  3. Java int -> String : String s = String.valueOf(i);
  4. 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;
}

最新文章

  1. python学习道路(day10note)(线程,进程)
  2. sqlalchemy中文乱码问题解决方案
  3. Droidicon – 1600+ 漂亮的 Android 图标
  4. 阿里云 CentOS6.5 ssh连接慢的解决方案
  5. 锁ReaderWriterLockSlim介绍
  6. Python Django 开发 3 数据库CURD
  7. Qt的学习资料比起其它C/C++的GUI组件来说已经算很全的了
  8. STM32F0xx_USART收发配置详细过程
  9. Android - Facebook KeyHash 設定
  10. 动态加载下拉框列表并添加onclick事件
  11. [小知识点]IE6下不支持:hover的解决方法
  12. ural 1100. Final Standings(数据结构)
  13. Java经典编程题50道之五
  14. STL:vector容器用法详解
  15. mysql常见安全加固策略
  16. FreeMarker生成Word文档
  17. TFC2017 腾讯Web前端大会参会小结
  18. webservice之wsdl
  19. All the Apache Streaming Projects: An Exploratory Guide
  20. Web Service测试工具小汇

热门文章

  1. Gamma函数深入理解
  2. java 数组和集合
  3. mac shell终端编辑命令行快捷键——行首,行尾
  4. IDEA添加作者和时间信息
  5. AspectJ框架基于注解的AOP实现
  6. Linux内核启动流程与模块机制
  7. DOS下读取smbios的汇编程序(通过搜索memory)
  8. centos7.2 开机启动脚本
  9. Python 一些有趣的技巧,包括协程例
  10. bzoj2595 / P4294 [WC2008]游览计划