Showing posts with label JavaScript. Show all posts
Problem Name : Plus One
Platform : leetcode
Language: Javascript
Link : Plus One
In this problem you have a number which represented by an array where every element of the array represents a digit of the number, for example the number 123 is represented as [1 , 2 , 3].
You are required to increase the given number by 1 and return it as an array.
So your gonna add one to the last element of the array and boom you solved the problem..... well if you do that and submit your answer you will get an error because if the last digit is 9 say the number is [1 , 2 , 9] and increased by 1 it will be [1 , 2 , 10] instead of [1 , 3 , 0]. in that case i we found that the last digit is 9 we gonna make it 0 and increase the next digit by one and we good to go..
Oops.. you get another error๐๐. because if we get a number that the next digit is also 9 say 1299, we will get the same problem but on a different digit this time, the solution is simple we need to loop through the digits and do the last step on every one of them.
Well we still have a little problem here if we got a number that all of it's digits is 9s say 99, according to our code the answer will be 00 , and the solution to that is to make the firist digit 1 and add 0 to the back of the array.
Enough talking and let's dive to the algorithm:
- loop through the array starting from the last element(firist digit).
- Creat an if statment inside the for loop, if the digit is not 9 we increase it by 1 and break (exit) the for loop.
- If it's 9 we make it 0 and repeat the steps on the next digit until we break the loop.
- The last step is to check if the first elemnt of the array is 0 we make it 1 and push 0 in the back of the array.
And yay✌
66. Plus One
- First creat an array to contain the numbers (answer).
- Make for loop to start filling the array with (n) elements.
- We use the modulo operator(%) to see if the number is divisible by 3 or 5 or both.
- If the number is divisible by 3 and 5 we push : "FizzBuzz" into the array.
- If it is divisible by 3 we push : "Fizz".
- If it is divisible by 5 we push : "Buzz".
- And if it is not divisible by any then we simply push the number as a string into the array.
- When we finish the numbers we return the (answer) array.
412. Fizz Buzz
Language: Javascript
- if the index is 1 or 0 the returned value will be the same as index itself.
- but if the index is larger we will need to create the Fibonacci sequence (fibSequance).
- we will create an array that have 0 and 1 as the first two elements.
- then we will loop through the array starting from the third element(2 as index).
- and we will push into the array the sum of the two previous elements (index (i-1) and (i-2)).
- at last we will return the element on the (n) index.