Given a very large number represented as a string num, determine whether it is divisible by 11.
A number is divisible by 11 if the alternating sum of its digits (starting from the rightmost digit) is divisible by 11. Specifically, compute the difference between the sum of digits at odd positions (from the right, 1-indexed) and the sum of digits at even positions (from the right). If this difference is divisible by 11, the number is divisible by 11.
Return True if the number is divisible by 11, otherwise return False.
Function Signature
def is_divisible_by_11(num: str) -> bool:
Rules
-
num
is a non-negative integer written in base 10. Position 1 is the rightmost digit.
-
"0"
counts as divisible by 11, so it returns
True
.
Constraints
-
1 <= len(num) <= 10^5
-
num
consists only of digits (
'0'
to
'9'
).
-
num
does not have leading zeros except for the number
"0"
itself.
Examples
Input: num = "121"
Output: True
The alternating sum from right to left is 1 - 2 + 1 = 0. Since 0 is divisible by 11, the answer is True. Indeed, 121 / 11 = 11.
Input: num = "123"
Output: False
The alternating sum from right to left is 3 - 2 + 1 = 2. Since 2 is not divisible by 11, the answer is False. Indeed, 123 / 11 = 11.18....
Input: num = "918082"
Output: True
From right to left the sum is 2 - 8 + 0 - 8 + 1 - 9 = -22, which is a multiple of 11 even though it is negative. Indeed, 918082 / 11 = 83462.