Problem


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
    isLucky(n) = true;
  • For n = 239017, the output should be
    isLucky(n) = false.


Input/Output

  • [input] integer n

    A ticket number represented as a positive integer with an even number of digits.

    Guaranteed constraints:
    10 ≤ n < 106.

  • [output] boolean

    true if n is a lucky ticket number, false otherwise.


Solution

def isLucky(n):

number = str(n)


sh = number[:int(len(number)/2)]

he = number[int(len(number)/2):]


return sum([int(i) for i in sh]) == sum([int(i) for i in he])


*number : 인덱스 슬라이싱을 하기 위해 integer로 들어오는 입력 값을 string으로 변환한 값을 저장하는 변수입니다.

*sh : start to half, 처음부터 중간까지 문자열을 저장하는 변수입니다.

*he : half to end : 중간부터 끝까지 문자열을 저장하는 변수입니다.

Input 값으로 입력된 숫자의 절반과 나머지의 합이 같은지를 판단하는 문제입니다.

인덱스 슬라이싱을 위해 Input값을 String으로 변환하고, 변환한 상태에서 절반씩 나누어 변수에 저장해주었습니다.

for문을 사용하여 각각의 숫자 값을 integer로 변환 후 리스트로 반환하고, 반환한 리스트를 더한 값을 서로 비교하여 문제를 해결할 수 있습니다.


'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] reverseParentheses  (0) 2018.02.20
[Algorithm] sortByHeight  (0) 2018.02.09
[Algorithm] commonCharacterCount  (0) 2018.02.09
[Algorithm] allLongestStrings  (0) 2018.02.09
[Algorithm] matrixElementsSum  (0) 2018.02.08

+ Recent posts