code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

258 Add Digits

/**
 * 
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
 * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
 * 
 * Example:
 * 
 * Input: 38
 * Output: 2 
 * Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
 *              Since 2 has only one digit, return it.
*/

function addDigits(num) {
  while(num >= 10){
    num = Math.floor(num/10) + num %10
  }
  return num
}

test('add Digits', () => {
  expect(addDigits(38)).toEqual(2)
});

Created 2020-04-11T09:19:42+00:00 · Edit