Code Signal – 幸运数(is lucky)

Code Signal – 幸运数(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 isLucky(n) = true;
For n = 239017, the output should be isLucky(n) = false.
Input/Output:

[execution time limit] 4 seconds (js)

[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.

解题思路
总觉得在 Leetcode 上刷过这道题,主要的考点还是在于 字符串 和 数字 之间的转换。

接受的参数是 1230,是数字,要做的第一步就是将其转换成字符串 “1230”。

随后就是做两个迭代,一个迭代前半部分,获取 1 + 2 的值,另一个迭代后半部分,获取 3 + 0 的值。做迭代的时候就需要将 字符 转换为 数字,否则就是 12 对比 30,而不是 3 对比 3。

 

class Solution:
    def isLucky(n):
        print(“——————–“)
        print(n)
        while n > 0:
        number_array.append(n % 10)
        n = int (n / 10)
        print(number_array)
        length = len(number_array)
        print(length)
        sum_of_left = 0
        # count left
        for i in range(length//2):
        sum_of_left += number_array[i]
        sum_of_right = 0
        for i in range(length//2):
        sum_of_right += number_array[length – i -1]
        print(sum_of_left)
        print(sum_of_right)
        return sum_of_left == sum_of_right
isLucky(1230)
isLucky(239017)
No Comments

Post A Comment