[JS Practice] Summing a number’s digits(对各个位数上的数字求和)

Title :

Summing a number’s digits(对各个位数上的数字求和)


Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number’s decimal digits. For example:

  sumDigits(10); // Returns 1
  sumDigits(99); // Returns 18
  sumDigits(-32); // Returns 5

Let’s assume that all numbers in the input will be integer values.

My solution :

function sumDigits(number) {
  return eval(Math.abs(number).toString().split("").join("+"));

Or a function easy to read :

function sumDigits(number) {
  // Get the absolute value even if it is a positive or negative number
  // 对数字取正数(此处只考虑整数,带小数的话可以考虑toFixed方法)
  var num = Math.abs(number);
  // Convert the number to string and split it into pieces
  // 把数字类型转换成字符类型,以便于分割每个位数上的数字
  var a = num.toString().split("");
  // Join all pieces of numbers with +
  // 对分割好的数字组成的数组进行+操作,也就是求sum
  return eval(a.join("+"));

此练习的重点在于考察javascript中的一个基础方法的使用,如split, eval, join等等。

Ref. from codewars


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s