Skip to content
This repository was archived by the owner on Jan 23, 2024. It is now read-only.

Commit 1ffbebf

Browse files
author
Lanh Hoang
committed
InterviewBit - Math: FizzBuzz solution and README
1 parent 28130ff commit 1ffbebf

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

Math/fizzbuzz/README.md

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# FizzBuzz
2+
3+
## Problem:
4+
Fizzbuzz is one of the most basic problems in the coding interview world. Try to write a small and elegant code for this problem.
5+
6+
Given a positive integer `A`, return an array of strings with all the integers from `1` to `N`.
7+
8+
But for multiples of `3` the array should have "Fizz" instead of the number.
9+
10+
For the multiples of `5`, the array should have "Buzz" instead of the number.
11+
12+
For numbers which are multiple of `3` and `5` both, the array should have "FizzBuzz" instead of the number.
13+
14+
Look at the example for more details.
15+
16+
Example:
17+
18+
**Input:**
19+
```
20+
A = 5
21+
```
22+
23+
**Output:**
24+
```
25+
[1 2 Fizz 4 Buzz]
26+
```
27+
28+
## Approach:
29+
30+
While iterating from `1` to `N`, you need to check the following conditions in sequence:
31+
32+
-Check whether the number is divisible by `3` and `5`, if that is the case, print "FizzBuzz".
33+
34+
-Check whether the number is divisible by `3`, in that case, print "Fizz".
35+
36+
-Next, check whether the number is divisible by `5`, in that case print "Buzz".
37+
38+
-Otherwise, print the number.
39+
40+
Time Complexity: `O(N)`
41+
Space Complexity: `O(N)`

Math/fizzbuzz/fizzbuzz.rb

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# https://www.interviewbit.com/problems/fizzbuzz
2+
3+
class Solution
4+
# @param a : integer
5+
# @return an array of strings
6+
def fizzBuzz(a)
7+
res = []
8+
1.upto(a).each do |num|
9+
if num % 3 == 0 && num % 5 == 0
10+
res.push('FizzBuzz')
11+
elsif num % 3 == 0
12+
res.push('Fizz')
13+
elsif num % 5 == 0
14+
res.push('Buzz')
15+
else
16+
res.push(num)
17+
end
18+
end
19+
res
20+
end
21+
end
22+
23+
class Solution
24+
# @param a : integer
25+
# @return an array of strings
26+
def fizzBuzz(a)
27+
(1..a).map do |n|
28+
str = ''
29+
str += 'Fizz' if n % 3 == 0
30+
str += 'Buzz' if n % 5 == 0
31+
str.empty? ? n : str
32+
end
33+
end
34+
end
35+
36+
a = 5
37+
p Solution.new.fizzBuzz(a)

0 commit comments

Comments
 (0)