Created
June 21, 2020 01:43
-
-
Save YounglanHong/58c3ea6b814b38039f1ea9cc6f8cba58 to your computer and use it in GitHub Desktop.
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 numbers = { | |
| "1": 1, | |
| "2": 2, | |
| "3": 3, | |
| "4": 4, | |
| "5": 5, | |
| "6": 6, | |
| "7": 7, | |
| "8": 8, | |
| "9": 9, | |
| "0": 0, | |
| }; | |
| function add(str1, str2) { | |
| const num1 = str1.length >= str2.length ? str1 : str2; | |
| const num2 = str1.length < str2.length ? str1 : str2; | |
| let result = []; | |
| let carry = 0; | |
| let strToNum1 = 0; | |
| let strToNum2 = 0; | |
| let sum = 0; | |
| for (let i = num1.length - 1; i >= 0; i--) { | |
| strToNum1 = numbers[num1[i]]; | |
| let diff = i - (num1.length - num2.length); | |
| strToNum2 = (diff >= 0 && diff < num2.length) ? numbers[num2[diff]] : 0; | |
| sum = strToNum1 + strToNum2 + carry; | |
| if (sum >= 10) { | |
| sum = sum - 10; | |
| carry = 1; | |
| } else { | |
| carry = 0; | |
| } | |
| result.push(sum); | |
| } | |
| if (carry === 1) { | |
| result.push(carry); | |
| } | |
| return result.reverse().join(""); | |
| } | |
| const argList = process.argv.slice(2); | |
| console.log(add(argList[0], argList[1])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment