LeetCode-in-Java

3340. Check Balanced String

Easy

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.

Example 1:

Input: num = “1234”

Output: false

Explanation:

Example 2:

Input: num = “24123”

Output: true

Explanation:

Constraints:

Solution

public class Solution {
    public boolean isBalanced(String num) {
        int diff = 0;
        int sign = 1;
        int n = num.length();
        for (int i = 0; i < n; ++i) {
            diff += sign * (num.charAt(i) - '0');
            sign = -sign;
        }
        return diff == 0;
    }
}