I have been working on a code exercise that involves creating a function expandedForm
to handle a number parameter. The examples provided below should help clarify the task at hand.
expandedForm(12); // Should return '10 + 2'
expandedForm(42); // Should return '40 + 2'
expandedForm(70304); // Should return '70000 + 300 + 4'
This is my initial solution:
function expandedForm(num) {
// Your code here
let numStr = num.toString().split('');
for(let i = 0 ; i < numStr; i++ ){
for(let y = numStr.length; y > 1; y--){
numStr[i] += '0';
// console.log(y); use this to debug y, and no y value print out from console
}
}
return numStr.join('+')
}
console.log(expandedForm(23));
When I test expandedForm(23), the result is '2+3' and the value of y isn't printed to the console. Can anyone identify what's wrong with my approach? Thank you.
Solution
Thank you to everyone who provided feedback. It was pointed out that my y variable
initialization in the for loop was incorrect, as well as the condition i < numStr
(silly mistake).
After reviewing my code and taking inspiration from some suggestions, here is my final solution:
function expandedForm(num) {
// Your code here
let numStr = num.toString().split('');
for(let i = 0 ; i < numStr.length; i++ ){
for(let y = numStr.length - i; y > 1; y--){
numStr[i] += '0';
// console.log(y); use this to debug y, and no y value print out from console
}
}
numStr = numStr.filter(value => !value.startsWith(0));
return numStr.join(' + ')
}
console.log(expandedForm(23));