code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

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