LintCode-【容易】9.Fizz Buzz问题

给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:

  • 如果这个数被3整除,打印fizz.
  • 如果这个数被5整除,打印buzz.
  • 如果这个数能同时被35整除,打印fizz buzz.
样例

比如 n = 15, 返回一个字符串数组:

[
  "1", "2", "fizz",
  "4", "buzz", "fizz",
  "7", "8", "fizz",
  "buzz", "11", "fizz",
  "13", "14", "fizz buzz"
]
C/C++: vector<string> 加两个标志变量搞定
class Solution {
public:
	/*
	* @param n: An integer
	* @return: A list of strings.
	*/
	vector<string> fizzBuzz(int n)
	{
		// write your code here
		vector<string> fb;
		int count = 0;
		for (int i = 1; i <= n; i++)
		{
			bool Index3 = false, Index5 = false;
			if (i % 3 == 0)  Index3 = true;
			if (i % 5 == 0)  Index5 = true;

			if (!Index3&&!Index5)         fb.push_back(to_string(i));
			else if (Index3&&!Index5)     fb.push_back("fizz");
			else if (!Index3&&Index5)     fb.push_back("buzz");
			else                          fb.push_back("fizz buzz");
			 
		}
		return fb;

	}
};


2.python:  注意数组的初始化
class Solution:
    """
    @param n: An integer as description
    @return: A list of strings.
  
    """
    def fizzBuzz(self, n):
        results = []
        for i in range(1, n+1):
            if i % 15 == 0:
                results.append("fizz buzz")
            elif i % 5 == 0:
                results.append("buzz")
            elif i % 3 == 0:
                results.append("fizz")
            else:
                results.append(str(i))
        return results

java:
 ArrayList<String>
public class Solution {
    /*
     * @param n: An integer
     * @return: A list of strings.
     */
    public List<String> fizzBuzz(int n) {
        // write your code here
        ArrayList<String> results = new ArrayList<String>();
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) {
                results.add("fizz buzz");
            } else if (i % 5 == 0) {
                results.add("buzz");
            } else if (i % 3 == 0) {
                results.add("fizz");
            } else {
                results.add(String.valueOf(i));
            }
        }
        return results;
    }
}
有关Java:ArrayList用法,可以看看:https://www.cnblogs.com/bayes/p/5474728.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值