leetcode412 笔记

  1. Fizz Buzz
    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”.
    编写一个用字符串表示数字从1到n的程序。
    但是对于三的倍数,应该输出“Fizz”,对于五点倍数输出“Buzz”, 对于三和五的公倍数输出“FizzBuzz”。
class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> result;
        for(int i=1;i<=n;i++){
            if(i%3==0&&i%5!=0)
                result.push_back("Fizz");
            else if(i%3!=0&&i%5==0)
                result.push_back("Buzz");
            else if(i%3==0&&i%5==0)
                result.push_back("FizzBuzz");
            else
                result.push_back(to_string(i));
        }
        return result;
    }
};

1、string to_string (int val);
2、字符串string用双引号,字符char用单引号哦~
(“a”是一个字符串,它包含字符a和\0,‘a’只表示字符a。字符串映射ascii码,其实就是数字。)

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> result(n);//初始化为n个空字符串
        for(int i=1; i<=n; ++i)
        {
            if(i%3 == 0)//是3
            {
                result[i-1] += "Fizz";//字符串的相加
            }
            if(i%5 == 0)//也是5
            {
                result[i-1] += "Buzz";
            }
            if(result[i-1] == "")//非3非5
            {
                result[i-1] += to_string(i);
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值