0

I was attempting a coding practice where I had to take a two digit integer, split the integer into its two digits and add those digits.

function addTwoDigits(n) {
var n = n
var string = n.toString()
var split = string.split("")
var integer= split.map(Number)
var z = integer[0]+integer[1]
console.log(z)

}

The output of my code was correct on each of the tests, but the code checks still failed. If anyone can provide some insight into why, I would appreciate it.

6
  • How does the code check checks your code? Does it specify a specific type that your answer needs to be in? Commented Apr 21, 2020 at 21:46
  • 2
    What is the point of var n = n ? Commented Apr 21, 2020 at 21:48
  • 1
    You could do that in a single line function addTwoDigits(n) {return Math.floor(n/10) + (n%10));} Commented Apr 21, 2020 at 21:52
  • @CedricCholley Thank you that worked great, I definitely will have to look more into Math.floor Commented Apr 21, 2020 at 22:04
  • @AvivLo it checks my code against random double digit integers and sees if the output of my code matches the correct answers or expected output based on those values Commented Apr 21, 2020 at 22:05

3 Answers 3

2

You could write the function this way

function addTwoDigits(n) {
    return Math.floor(n/10) + (n%10));
}
Sign up to request clarification or add additional context in comments.

Comments

0

I have encountered a similar issue before. The solution for me was returning the value, rather than logging it to the console.

Instead of console.log(z) try return z

Comments

0

Not sure what you mean by "but the code checks still failed". Here's a oneliner for n-digit numbers, using a reducer:

const sumOfIndividualDigits = n => 
  [...`${n}`]
  // ^ convert to Array of strings
  .map(Number)
  //   ^convert element (back) to Numbers
  .reduce( (acc, value) => acc + value, 0);
  //       ^ reduce to 1 value (sum)
  
console.log(sumOfIndividualDigits(22));
console.log(sumOfIndividualDigits(12345678));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.