String concatenation approach

This commit is contained in:
Vitor Oliveira 2021-03-20 11:04:34 -07:00
parent 12e2addd81
commit ea7ea7ec72

View file

@ -54,3 +54,54 @@ fizz_buzz(n)
# "14",
# "FizzBuzz"
# ]
#
# Approach 2: String Concatenation
#
# Algorithm
#
# Instead of checking for every combination of these conditions,
# check for divisibility by given numbers i.e. 3, 5 as given in the
# problem. If the number is divisible, concatenate the corresponding
# string mapping Fizz or Buzz to the current answer string.
#
# For eg. If we are checking for the number 15, the steps would be:
#
# Condition 1: 15 % 3 == 0 , num_ans_str = "Fizz"
# Condition 2: 15 % 5 == 0 , num_ans_str += "Buzz"
# => num_ans_str = "FizzBuzz"
#
# So for FizzBuzz we just check for two conditions instead of three
# conditions as in the first approach.
#
# Similarly, for FizzBuzzJazz now we would just have three
# conditions to check for divisibility.
# Complexity Analysis
#
# Time Complexity: O(N)
# Space Complexity: O(1)
# @param {Integer} n
# @return {String[]}
def fizz_buzz(n)
str = []
n.times do |i|
i += 1
num_str = ''
num_str += 'Fizz' if i % 3 == 0
num_str += 'Buzz' if i % 5 == 0
num_str = i.to_s if num_str == ''
str.push(num_str)
end
str
end
n = 15
puts(fizz_buzz(n))