KatInterview

Determine Divisibility by 8 for Large Numeric Strings

Math & Bit ManipulationAuto-graded · 21 test cases
EasyAuto-gradedMath & Bit Manipulationstringsmath-bitsmath

Last updated

Evaluate whether a very large non-negative integer string is divisible by 8 without converting the entire string into an integer.

Given a non-negative integer represented as a string s, determine whether the integer is evenly divisible by 8.

Because s may be exceptionally long, you should avoid parsing the entire string into a numerical type (e.g., calling int(s) on the full input is not permitted).

Return True if the number is divisible by 8, and False otherwise.

Constraints

  • 1 <= len(s) <= 10^6
  • s consists exclusively of digit characters ('0' through '9').
  • s may contain leading zeros (for example, "00024").
  • Direct conversion of the full string s to an integer is prohibited.

Examples

Example 1

Input: is_divisible_by_8('16')

Output: True

Example 2

Input: is_divisible_by_8('123')

Output: False

Example 3

Input: is_divisible_by_8('1000')

Output: True

Hints

Hint 1

Recall that 1000 is evenly divisible by 8 ($1000 = 8 \times 125$). What does this imply about higher positional powers of 10?

Hint 2

Since any multiple of 1000 contributes zero to the remainder modulo 8, only a small suffix of the string affects divisibility.

Hint 3

Consider how many trailing digits you actually need to examine, including when the input length is less than 3.