VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-large-number-divisible-5-not/

⇱ Check if a large number is divisible by 5 or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a large number is divisible by 5 or not

Last Updated : 4 Jun, 2026

Given a number s in the form of string, the task is to check if the number is divisible by 5. 

Examples: 

Input : s = 56945255
Output : true

Input : s = 12345
Output : true

Input : s = 36358839596
Output : false

[Naive Approach] String to Integer Conversion - O(n) Time and O(1) Space

Convert the given string to an integer by iterating through each digit, then check if it's divisible by 5 using modulo operator. This approach might cause overflow for very large numbers.

  • Initialize num = 0.
  • Traverse each character in string.
  • Update num = num × 10 + (digit).
  • Return true if num % 5 == 0 else false.

Output
1

[Optimal Approach] Last Digit Check - O(1) Time and O(1) Space

A number is divisible by 5 if and only if its last digit is 0 or 5. Since the number can be very large (given as string), directly check the last character instead of converting to integer.

  • Get last character of string using s.back().
  • Return 1 if last digit is '0' or '5'.
  • Return 0 otherwise.

Output
1
Comment