Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // tickets are lucky when sum of first half equals sum of second half
- const isLucky = n => {
- // min is 10 and we know it's false
- if (n === 10) return false;
- // store digits in an array
- const digitCorral = [];
- // use modulo, division and Math.trunc
- while (n > 0) {
- // push reverses the order but that doesn't matter
- // since the sum of each half will still be the same
- digitCorral.push(n % 10);
- n /= 10;
- n = Math.trunc(n);
- }
- // get sum of first half of array
- const firstHalf = digitCorral
- .slice(0, digitCorral.length / 2)
- .reduce(function(a, b) {
- return a + b;
- });
- // get sum of second half of array
- const secondHalf = digitCorral
- .slice(digitCorral.length / 2, digitCorral.length)
- .reduce(function(a, b) {
- return a + b;
- });
- // return a boolean
- return firstHalf === secondHalf;
- };
Add Comment
Please, Sign In to add comment