problem no 51:find the remainder when the string is divided by 7.

 QUESTION:

Remainder with 7
Basic Accuracy: 46.43% Submissions: 9141 Points: 1

Given a number as string(n) , find the remainder of the number whe it is divided by 7

Example 1:

Input:
5
Output:
5

 

Example 2:

Input:
8
Output:
1

 

 

 // IS FOR COMMENT.

ANSWER:

int remainderWith7(string num)
{
    // This series is used to find remainder with 7
    int series[] = {1, 3, 2, -1, -3, -2};
 
    // Index of next element in series
    int series_index = 0;
 
    int result = 0;  // Initialize result
 
    // Traverse num from end
    for (int i=num.size()-1; i>=0; i--)
    {
        /* Find current digit of nun */
        int digit = num[i] - '0';
 
        // Add next term to result
        result += digit * series[series_index];
 
        // Move to next term in series
        series_index = (series_index + 1) % 6;
 
        // Make sure that result never goes beyond 7.
        result %= 7;
    }
 
    // Make sure that remainder is positive
    if (result < 0)
      result = (result + 7) % 7;
 
    return result;
}

 

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.