作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

https://leetcode.com/problems/fizz-buzz/

  • Total Accepted: 31093
  • Total Submissions: 53272
  • Difficulty: Easy

##Question

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"
]

题目大意

从1~n这么多数字中中,如果某个位置是3的倍数,把这个数字换成Fizz,如果是5的倍数,把这个数字换成Buzz,如果既是3的倍数又是5的倍数,换成FizzBuzz.

解题方法

方法一:遍历判断

思路很简单,判断是否能特定位置的数字是否能被3和5整除即可。

class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
ListReturn = [];
x = 1
while x <= n:
if x % 3 == 0 and x % 5 == 0:
ListReturn.append("FizzBuzz")
elif x % 3 == 0:
ListReturn.append("Fizz")
elif x % 5 == 0:
ListReturn.append("Buzz")
else:
ListReturn.append(str(x))
x += 1
return ListReturn

AC:69 ms

感觉好繁琐,python应该可以很简单。所以参考了别人的跟进如下。

class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return ["Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0)
+ str(i) * (i % 3 != 0 and i % 5 != 0)
for i in range(1, n + 1)]

AC:96 ms

嗯。这个看起来舒服多了。

方法二:字符串相加

如果是5的倍数,就把结果字符串后面加上Buzz即可。这里不能使用elif的判断,因为是15既是3的倍数又是5的倍数,所以需要加上两个字符串。

class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
for i in range(1, n + 1):
pos = ""
if i % 3 == 0:
pos += "Fizz"
if i % 5 == 0:
pos += "Buzz"
if not pos:
pos = str(i)
res.append(pos)
return res

方法三:字典

把方法二的判断进行了优化,使用字典保存3和5的字符串的结果对应。

class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
strmap = {3 : "Fizz", 5 : "Buzz"}
for i in range(1, n + 1):
pos = ""
for j in [3, 5]:
if i % j == 0:
pos += strmap[j]
if not pos:
pos = str(i)
res.append(pos)
return res

日期

2017 年 1 月 2 日
2018 年 11 月 8 日 —— 项目进展缓慢

最新文章

  1. MySQL 优化之 MRR (Multi-Range Read:二级索引合并回表)
  2. win10下安装USB-Blaster哈希值错误
  3. 第十一篇、HTML5隐藏播放器播放背景音乐
  4. ImageList半透明,Alpha通道bug处理。
  5. hdu 2289 Cup (二分法)
  6. js 跨浏览操作
  7. Java编程之字符集问题研究
  8. eclipese with gdbserver and Jlink configuration
  9. Visual Studio 2015 &amp; C#6.0 试用报告,持续更新。
  10. POJ 3139 Balancing the Scale
  11. JavaScript动态加载资源【js|css】示例代码
  12. SCU 4438 Censor KMP/Hash
  13. Git—推送代码至Github
  14. 页面加载过渡页 loading plugin css
  15. Git抽取版本之间的差异,打包解压
  16. LabVIEW(四):数据存储和文件IO
  17. MD5盐值加密
  18. PHP获取文件大小的方法详解
  19. Windows平台交叉编译Arm Linux平台的QT5.7库
  20. 用setup.py安装第三方包packages

热门文章

  1. 【GWAS】如何计算显著关联位点的表型解释率PVE(phenotypic variation explained)?
  2. 【豆科基因组】普通豆/菜豆/四季豆Common bean (Phaseolus vulgaris L.) 基因组
  3. 基因组共线性分析工具MCScanX
  4. EXCEL-批量修改列宽
  5. ab命令执行压力测试
  6. A Child&#39;s History of England.4
  7. acknowledge
  8. Android获取通知栏的高度
  9. Linux基础命令---get获取ftp文件
  10. CentOS Linux下编译安装MySQL