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.
Input: num ="1234"Output: falseExplanation:
* The sum of digits at even indices is`1 + 3 == 4`, and the sum of digits at odd indices is`2 + 4 == 6`.* Since 4is not equal to 6,`num`is not balanced.
Input: num ="24123"Output: trueExplanation:
* The sum of digits at even indices is`2 + 1 + 3 == 6`, and the sum of digits at odd indices is`4 + 2 == 6`.* Since both are equal the `num`is balanced.
A string is balanced if the sum of digits at even indices equals the sum at odd indices. We can iterate through the string, summing digits at even and odd indices separately, and compare the results.
classSolution {
publicbooleanisBalanced(String num) {
int even = 0, odd = 0;
for (int i = 0; i < num.length(); i++) {
int d = num.charAt(i) -'0';
if (i % 2 == 0) even += d;
else odd += d;
}
return even == odd;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defisBalanced(self, num: str) -> bool:
even =0 odd =0for i, ch in enumerate(num):
d = int(ch)
if i %2==0:
even += d
else:
odd += d
return even == odd