DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Edited on

#18 - Previous multiple of three CodeWars Kata (7 kyu)

Instructions

Given a positive integer n: 0 < n < 1e6, remove the last digit until you're left with a number that is a multiple of three.

Return n if the input is already a multiple of three, and return null if no such number exists.

Examples

1 => null
25 => null
36 => 36
1244 => 12
952406 => 9


My solution:

const prevMultOfThree = n => {
  let arr = n.toString().split('')

  for(let i = 0; i<arr.length; i++){
    for(let j = 0; j<arr.length; i++){
      let sum = +arr.join('')
      if( sum % 3 === 0) return sum 
      arr.pop()
    }

    return null
  }

}

Enter fullscreen mode Exit fullscreen mode

Explanation

First I splitted the number into an string array

let arr = n.toString().split('')


Then after that I used a loop that iterated until i is equal to the array length.
Inside of this array I used anothe for loop that still iterated the same array, inside of this loop I made the variable "sum" that is equal to the array joined and converted it to a number with the + operator, after that I added a conditional that checked if it is divisible by 3, if it is divisible by 3 it will return 3, but if not it will continue the loop but with the array without the last element, using arr.pop()

for(let j = 0; j<arr.length; i++){
let sum = +arr.join('')
if( sum % 3 === 0) return sum
arr.pop()
}


if the loop is over and the array is still empty, it means that any number was divisible by 3, so it returns null

return null


Comment how would you solve this kata and why? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (0)