[LeetCode] Check Balanced String

3340. Check Balanced String

You are given a string num consisting of only digits. A string of digits is called balanced if the sum of the digits at even indices is equal to the sum of digits at odd indices.

Return true if num is balanced, otherwise return false.

1
2
3
4
5
6
7
8
9
10
11
package main

func isBalanced(num string) bool {
sum := 0
sign := 1
for i := 0; i < len(num); i++ {
sum += int(num[i]-'0') * sign
sign = -sign
}
return sum == 0
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/03/PS/LeetCode/check-balanced-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.