Created
January 31, 2022 22:12
-
-
Save jcolebot/c1d9f3e4430e0a54a600494745e65c0c to your computer and use it in GitHub Desktop.
Given a positive number as a string, multiply the number by 11 and also return it as a string without casting to an integer
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
| // Multiply by 11 | |
| // Given a positive number as a string, multiply the number by 11 and also return it as a string. However, there is a catch: | |
| // You are NOT ALLOWED to simply cast the numeric string into an integer! | |
| // Now, how is this challenge even possible? Despite this, there is still a way to solve it, and it involves thinking about how someone might multiply by 11 in their head. See the tips below for guidance. | |
| // Examples | |
| // multiplyBy11("11") ➞ "121" | |
| // multiplyBy11("111111111") ➞ "1222222221" | |
| // multiplyBy11("1213200020") ➞ "13345200220" | |
| // multiplyBy11("1217197941") ➞ "13389177351" | |
| // multiplyBy11("9473745364784876253253263723") ➞ "104211199012633638785785900953" | |
| // Tip | |
| // There is a simple trick to multiplying any two-digit number by 11 in your head: | |
| // Add the two digits together | |
| // Place the sum between the two digits! | |
| // Note if the total goes over, carry the sum on to the next digit | |
| // 23 * 11 | |
| // Add together 2 and 3 to make 5 | |
| // Place 5 between the two digits to make 253 | |
| // 77 * 11 | |
| // Add together 7 and 7 to make 14 | |
| // Place 4 between the two digits to make 747 | |
| // Carry the 1 to make 847 | |
| const num1 = "11"; | |
| function multiplyBy11(num1, num2) { | |
| let str1 = [...num1].reverse(), | |
| str2 = [...num2].reverse(), | |
| arr = [], | |
| i, j; | |
| for(i = 0; i < str1.length; i++) { | |
| for(j = 0; j < str2.length; j++) { | |
| if(!arr[i + j]) arr[i + j] = 0; | |
| arr[i + j] += str1[i] * str2[j]; | |
| if (arr[i + j] > 9) { | |
| if(!arr[i + j + 1]) arr[i + j + 1] = 0; | |
| arr[i + j + 1] += Math.floor(arr[i + j] / 10); | |
| arr[i + j] %= 10; | |
| } | |
| } | |
| } | |
| return arr | |
| .reverse() | |
| .filter((valid => (v, i, { length }) => valid = +v || valid || i + 1 === length)(false)) | |
| .join(' '); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment