JavaScript Square and Join Digits: Two Approaches Quiz
Two seeded ways to square each digit of an integer and concatenate the results (string split with map and join, plus a while-loop modulo extraction), with two companions on negative numbers and on returning a string.
491 views
14
Implement squareDigit(num) using string conversion: split the number into characters, square each digit, join them back together, and return the result as a Number.
Examples
Example 1:
Input: squareDigit(57)
Output: 2549
Explanation: 5*5 = 25 and 7*7 = 49, concatenating gives '2549', and Number('2549') is 2549.const squareDigit = (num) => {
// convert to string, split into digits, square each, join, return as Number
};
console.log(squareDigit(57)); // 2549
console.log(squareDigit(9119)); // 811181Implement squareDigit(num) using a while loop that extracts digits with % 10 and Math.floor(num / 10), builds the squared-digit string in reverse, and returns the parsed Number.
Examples
Example 1:
Input: squareDigit(57)
Output: 2549
Explanation: extracting from the right gives 7 then 5; squaring yields 49 and 25; prepending preserves the original digit order, so the joined string is '2549'.const squareDigit = (num) => {
// extract digits with % 10 in a while loop and prepend the squared digit to a result string
};
console.log(squareDigit(57)); // 2549
console.log(squareDigit(9119)); // 811181Extend squareDigit to handle negative integers by preserving the sign: squareDigit(-57) should return -2549. Implement this on top of the string-split approach.
Examples
Example 1:
Input: squareDigit(-57)
Output: -2549
Explanation: working with Math.abs strips the sign, then we multiply the final number by Math.sign(num).const squareDigit = (num) => {
// preserve sign with Math.sign(num) and operate on Math.abs(num)
};
console.log(squareDigit(-57)); // -2549
console.log(squareDigit(57)); // 2549
console.log(squareDigit(0)); // 0Refactor squareDigit to return a string instead of a Number. Why is this safer for very large inputs, and what is the new return value for squareDigit(99999999999) (eleven nines)?
Examples
Example 1:
Input: squareDigit(99999999999)
Output: '8181818181818181818181'
Explanation: each 9 squares to 81, and eleven 81s concatenated form the 22-character string above.const squareDigit = (num) => {
// return the joined string directly, no Number(...) wrap
};
console.log(squareDigit(99999999999));