Created
October 2, 2023 17:30
-
-
Save JoshuaRotimi/7dae39e9e1afc76284e869926d7f42a4 to your computer and use it in GitHub Desktop.
Add Operators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const add = (nums) => { | |
| const allNums = nums.toString().split("").map((num) => parseInt(num)); | |
| return allNums.reduce((acc, cur) => acc + cur, 0); | |
| }; | |
| const multiply = (nums) => { | |
| const allNums = nums.toString().split("").map((num) => parseInt(num)); | |
| return allNums.reduce((acc, cur) => acc * cur, 1); | |
| }; | |
| const stringify = (number, sign) => { | |
| const numberStrings = number.toString(); | |
| let str = ""; | |
| for (let i = 0; i < numberStrings.length; i++) { | |
| if (i === numberStrings.length - 1) { | |
| str = str + numberStrings[i]; | |
| } else { | |
| str = str + numberStrings[i] + sign; | |
| } | |
| } | |
| return str; | |
| }; | |
| const addOperators = (source, target) => { | |
| let possible = []; | |
| const addition = add(source); | |
| const product = multiply(source); | |
| if (addition === target) { | |
| possible.push(stringify(source, "+")); | |
| } | |
| if (product === target) { | |
| possible.push(stringify(source, "*")); | |
| } | |
| return possible; | |
| }; | |
| addOperators(123, 6); // ["1+2+3", "1*2*3"] | |
| addOperators(1234, 24); // ["1*2*3*4"] | |
| addOperators(3456237490, 9191); // [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment