LeetCode in Kotlin

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

class Solution {
    fun isBalanced(num: String): Boolean {
        var diff = 0
        var sign = 1
        val n = num.length
        for (i in 0 until n) {
            diff += sign * (num[i].code - '0'.code)
            sign = -sign
        }
        return diff == 0
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy