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
n = 1230, the output should be**solution(n) = true**;n = 239017, the output should be**solution(n) = false**.Input/Output
[execution time limit] 3 seconds (java)
[memory limit] 1 GB
[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.
boolean solution(int n) {
// 자릿 수 비교를 위한 int to String
String str = Integer.toString(n);
// 홀수 -> false
if (str.length() % 2 > 0) return false;
// 반으로 잘랐을 때, 앞은 헤드 뒤는 테일로 구분
int head = 0;
int tail = 0;
// 순회를 위한 스플릿
String [] arr = str.split("");
// 순회 한 번으로 끝내기 위한 tail index
int idx = arr.length - 1;
// 문자열을 int 로 변경하여 누적합
for (int i = 0; i < arr.length / 2; i ++) {
head += Integer.parseInt(arr[i]);
tail += Integer.parseInt(arr[idx--]);
}
// 같은 값이면 행운번호
if (head == tail) return true;
return false;
}