Last Updated: 29 Jul, 2022

Divisible Substrings

Easy
Asked in company
HashedIn

Problem statement

You are given a number in the form of a string ‘S’ of length ‘N’ consisting of characters from '0' to '9' (both inclusive) .

You must return the number of substrings that are divisible by 5. Some strings divisible by 5 are ‘5’, ‘370’, and ‘1000’.

Note :

A substring can start with a zero. The given number may also contain leading zeroes.

Example:

‘S'= ‘5203’

Here, four substrings are divisible by 5: ‘5’, ’520’, ‘20’, ‘0’.
Hence the answer is 4.
Input Format
First-line contains 'T', denoting the number of Test cases.

For each Test case:

The first line contains an integer ‘N’ denoting the string ‘S’ length.
The second line contains a string ‘S’ of size ‘N’.
Output format :
Return an integer denoting the total number of substrings whose integral value are divisible by 5. 
Note:-
You don't need to print anything. Just implement the given function.
Constraints :
1 <= 'T' <= 10
1 <= 'N' <= 10^5
'0' <= 'S[i]' <= '9'


Time Limit: 1 sec

Approaches

01 Approach

Approach:-


 

  • Every number whose unit digit is 0 or 5 is divisible by 5. Ex - 5, 75, 60 etc.
  • So, every substring that ends with a ‘0’ or ‘5’ is divisible by 5.
  • The count of all such substrings is our answer.


 

 Algorithm:-

  • Initialize a variable ‘answer’ with 0.
  • for i = 0 to N-1 :
    • for j = i to N-1:
      • If ‘s[j]’ == ‘0’ or ‘s[j]’ == ‘5‘ :
        • ‘answer’ = ‘answer’+1
  • Return ‘answer’.

02 Approach

Approach:-

 

  • Every number whose unit digit is 0 or 5 is divisible by 5. Ex - 5, 75, 60 etc.
  • So, Every substring that ends with a ‘0’ or ‘5’ is divisible by 5.
  • The count of all such substrings is our answer.

 

 

 Algorithm:-

  • Initialize a variable ‘answer’ with 0.
  • for i = 0 to N-1 :
    • If ‘S[i]’ == ‘0’ or ‘S[i]’ == ‘5‘ :
      • ‘answer’ = ‘answer’ + (‘i’+1)
  • Return ‘answer’.