📜  fizzbuzz hackerrank 解决方案 c++ - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:13.254000             🧑  作者: Mango

FizzBuzz Hackerrank Solution in C++ and JavaScript

FizzBuzz is a simple programming task often used in coding interviews to assess basic programming skills. The task is to write a program that prints the numbers from 1 to n, but for multiples of three, it should print "Fizz" instead of the number, and for multiples of five, it should print "Buzz". For numbers that are multiples of both three and five, the program should print "FizzBuzz".

Here are the solutions for the FizzBuzz problem in both C++ and JavaScript:

C++ Solution
#include <iostream>
using namespace std;

string fizzBuzz(int n) {
    string result = "";
    for (int i = 1; i <= n; i++) {
        if (i % 3 == 0 && i % 5 == 0) {
            result += "FizzBuzz ";
        } else if (i % 3 == 0) {
            result += "Fizz ";
        } else if (i % 5 == 0) {
            result += "Buzz ";
        } else {
            result += to_string(i) + " ";
        }
    }
    return result;
}

int main() {
    int n = 15;
    cout << fizzBuzz(n) << endl;
    return 0;
}

This C++ solution uses a simple loop to iterate from 1 to n and checks the divisibility of each number by 3 and 5 to determine whether to print "Fizz", "Buzz", or "FizzBuzz". It concatenates the result using the += operator and the to_string() function is used to convert the number to a string when it is not divisible by 3 or 5.

JavaScript Solution
function fizzBuzz(n) {
  let result = "";
  for (let i = 1; i <= n; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
      result += "FizzBuzz ";
    } else if (i % 3 === 0) {
      result += "Fizz ";
    } else if (i % 5 === 0) {
      result += "Buzz ";
    } else {
      result += i.toString() + " ";
    }
  }
  return result;
}

const n = 15;
console.log(fizzBuzz(n));

This JavaScript solution follows the same logic as the C++ solution but uses the console.log() function to print the result to the console.

Both solutions are efficient and provide the expected output for the FizzBuzz problem. These solutions can be easily modified to accommodate different ranges or requirements.