Skip to content

1927. Sum Game 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  bool sumGame(string num) {
    const int n = num.length();
    double ans = 0.0;

    for (int i = 0; i < n / 2; ++i)
      ans += getExpectation(num[i]);

    for (int i = n / 2; i < n; ++i)
      ans -= getExpectation(num[i]);

    return ans != 0.0;
  }

 private:
  double getExpectation(char c) {
    return c == '?' ? 4.5 : c - '0';
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public boolean sumGame(String num) {
    final int n = num.length();
    double ans = 0.0;

    for (int i = 0; i < n / 2; ++i)
      ans += getExpectation(num.charAt(i));

    for (int i = n / 2; i < n; ++i)
      ans -= getExpectation(num.charAt(i));

    return ans != 0.0;
  }

  private double getExpectation(char c) {
    return c == '?' ? 4.5 : c - '0';
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def sumGame(self, num: str) -> bool:
    n = len(num)
    ans = 0.0

    def getExpectation(c: str) -> float:
      return 4.5 if c == '?' else int(c)

    for i in range(n // 2):
      ans += getExpectation(num[i])

    for i in range(n // 2, n):
      ans -= getExpectation(num[i])

    return ans != 0.0