Solidity Exercise - FizzBuzz

Posted by Bourne's Blog - A Full-stack & Web3 Developer on May 14, 2024

FizzBuzz

// if n is divisible by 3, return “fizz” // if n is divisible by 5, return “buzz” // if n is divisible be 3 and 5, return “fizz buzz” // otherwise, return an empty string

Coding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.13;

contract FizzBuzz {
    function fizzBuzz(uint256 n) public pure returns (string memory) {
        // if n is divisible by 3, return "fizz"
        // if n is divisible by 5, return "buzz"
        // if n is divisible be 3 and 5, return "fizz buzz"
        // otherwise, return an empty string
        string memory s = "";
        if (n % 3 == 0) s = "fizz";
        if (n % 5 == 0) {
            if (bytes(s).length > 0) 
                s = string.concat(s, " ") ;
            s = string.concat(s, "buzz") ;
        }
        return s;
    }
}

Test

1
2
3
4
5
6
7
8
9
10
11
➜  FizzBuzz git:(main) ✗ forge test -vvv
[⠊] Compiling...
[⠒] Compiling 19 files with Solc 0.8.25
[⠑] Solc 0.8.25 finished in 593.04ms
Compiler run successful!

Ran 1 test for test/FizzBuzz.t.sol:FizzBuzzTest
[PASS] testFizzBuzz() (gas: 15537)
Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 4.65ms (296.42µs CPU time)

Ran 1 test suite in 142.28ms (4.65ms CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)

Reference: Solidity Exercise - FizzBuzz