LeetCode in Kotlin

1927. Sum Game

Medium

Alice and Bob take turns playing a game, with Alice starting first.

You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:

  1. Choose an index i where num[i] == '?'.
  2. Replace num[i] with any digit between '0' and '9'.

The game ends when there are no more '?' characters in num.

For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.

Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.

Example 1:

Input: num = “5023”

Output: false

Explanation: There are no moves to be made. The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.

Example 2:

Input: num = “25??”

Output: true

Explanation: Alice can replace one of the ‘?’s with ‘9’ and it will be impossible for Bob to make the sums equal.

Example 3:

Input: num = “?3295???”

Output: false

Explanation: It can be proven that Bob will always win. One possible outcome is:

Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.

Constraints:

Solution

class Solution {
    fun sumGame(num: String): Boolean {
        var count = 0
        var diff = 0
        val l = num.length
        for (i in 0 until num.length) {
            if (num[i] == '?') {
                count += if (i < l / 2) 1 else -1
            } else {
                if (i < l / 2) {
                    diff += num[i].code - '0'.code
                } else {
                    diff -= num[i].code - '0'.code
                }
            }
        }
        return diff * 2 != -9 * count
    }
}