Skip to content

Is Lucky

Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.

Given a ticket number n, determine if it's lucky or not.

Example

  • For n = 1230, the output should be

    is_lucky(n) = true
  • For n = 239017, the output should be

    is_lucky(n) = false

Solution

py
def is_lucky(n):
    s = str(n)
    l = len(s)
    h = l // 2

    return l % 2 == 0 and sum(map(int, s[:h])) == sum(map(int, s[h:]))


print(is_lucky(134008))
js
function isLucky(n) {
  let string = n.toString();
  let firstHalf = string.slice(0, string.length / 2);
  let secondHalf = string.slice(string.length / 2, string.length);
  let firstSum = 0;
  let secondSum = 0;

  for (let i = 0; i < firstHalf.length; i++) {
    firstSum += parseInt(firstHalf[i]);
    secondSum += parseInt(secondHalf[i]);
  }

  return firstSum === secondSum;
}

console.log(isLucky(134008));

my thoughts are neither my employer's nor my wife's