iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 7
1
自我挑戰組

見習村-30 Day CodeWars Challenge系列 第 7

見習村07 - Sum of Digits / Digital Root

  • 分享至 

  • twitterImage
  •  

07 - Sum of Digits / Digital Root

Don't say so much, just coding...

Instruction

Digital root is the recursive sum of all the digits in a number.

Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

Examples:

   16   -->  1 + 6 = 7
   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2

Ruby

Init

  def digital_root(n)
    # ...
  end

Sample Testing

  Test.assert_equals(digital_root(16), 7)
  Test.assert_equals(digital_root(942), 6)
  Test.assert_equals(digital_root(132189), 6)
  Test.assert_equals(digital_root(493193), 2)

Javascript

Init

  function digital_root(n) {
    // ...
  }

Sample Testing

  Test.assertEquals( digital_root(16), 7 )
  Test.assertEquals( digital_root(456), 6 )

Thinking

想法(1): 將傳進來的值,先切開之後進行相加
想法(2): 需要判斷如果是兩位數以上的話,還需要在進行上述的動作,可以聯想到遞迴

https://ithelp.ithome.com.tw/upload/images/20200922/20120826PSUp8bSOU0.jpg
圖片來源:Unsplash Alexis Brown

Hint & Reference

Solution

Ruby

  # Solution 1
  def digital_root(n)
    recursive = n.to_s.split('').map(&:to_i).sum
    recursive >= 10 ? digital_root(recursive) : recursive
  end
  
  # Solution 2
  def digital_root(n)
    return n if n < 10
    digital_root(n.to_s.chars.map(&:to_i).reduce(&:+))
  end
  
  # Solution 3
  def digital_root(n)
    n < 10 ? n : digital_root(n.to_s.chars.map(&:to_i).reduce(:+))
  end

Javascript

  // Solution 1
  function digital_root(n) {
    recursive = n.toString().split('').reduce((sum, s) => {
      return sum += Number(s);
    }, 0);
  
    return recursive < 10 ? recursive : digital_root(recursive);
  }
  
  // wait, what?
  function digital_root(n) {
    return (n - 1) % 9 + 1;
  }

上一篇
見習村06 - Character with longest consecutive
下一篇
見習村08 - Mexican Wave
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言