![]() |
VOOZH | about |
Given a number s represented as a string, determine whether the integer it represents is divisible by 13 or not.
Examples :
Input: s = "2911285"
Output: true
Explanation: 2911285 / 13 = 223945, which is a whole number with no remainder.Input: s = "27"
Output: false
Explanation: 27 / 13 ≈ 2.0769..., which is not a whole number (there is a remainder).
Table of Content
If the given number is small, we can easily check whether it is divisible by 13 by computing s % 13 and verifying if the result is 0.
Note: This method only works when the number fits within standard integer data types. For very large numbers (such as those represented as strings with hundreds or thousands of digits), this approach may lead to overflow or be unsupported, so a string-based method is required.
true
Time Complexity: O(n), n is length of s
Auxiliary Space: O(1)
A number is divisible by 13 if and only if the alternating sum of its 3-digit blocks, taken from right to left, is divisible by 13.
Step by Step approach -
"2911285" → "291128500" (after padding with two zeros)."291128500" → blocks: 500, 128, 291 (right to left order).+ on the rightmost block+ block , - block, + block, …+500 - 128 + 291.500 - 128 + 291 = 663.663 % 13 == 0 → divisible.true
Time Complexity: O(n), n is length of s
Auxiliary Space: O(1)
We process the number digit by digit from left to right, maintaining the remainder modulo 13 at each step using the formula:
rem = (rem * 10 + digit) % 13.
Step by Step Approach -
true
Time Complexity: O(n), n is length of s
Auxiliary Space: O(1)