Monday 6 August 2018

Sum Of Palindromic Numbers

QUESTION DESCRIPTION :

A number is called palindromic if its decimal representation is a palindrome. You are given a range, described by a pair of integers L and R. Find the sum of all the palindromic numbers lying in the range [L,R], inclusive of both the extremes.

Input Format :

The first line contains an integer T, denoting the number of test cases.
The description of T test cases follow:
  • Each line of test cases contains 2 numbers L and R denoting the lower and upper bound of the numbers for which you have to calculate the sum.
Output Format :

For each line of input, print a single integer which is equal to the sum of the palindromic numbers.

TEST CASE 1

INPUT

2
1 10
123 150

OUTPUT

sum is 45
sum is 272

EXPLANATION :

The question asks the programmer to send the sum of all the numbers that are palindromic in nature. So in order to solve this question we will check every number for the palindromic property and add it to the resulting sum if the number is a palindrome.

ALGORITHM :

Although there are quite a few algorithms that can be used to solve this, we will be using a simple one. Instead of checking each half of the number for similarity, we will be reversing the number and then checking if it is equal to the given number. If yes, then the number will be added to the resulting sum.

Steps:
  1. Take the input T for the number of test cases.
  2. Loop T times
    1. For each test case take L an R as input
  3. Start a loop from L till R and check palindrome constaint (done in the isPal function)
    1. For each number of the loop, calculate the reverse of it.
      • Reverse calculation:
        1. Take number and mod (%) it by 10 this gives you the first ones digit
        2. Multiply rev (Intially 0) by 10 and add the above digit to it
        3. Divide the original number by 10 to remove the previous digit.
        4. Goto step 3.1.1 until there is atleast a digit left in the number
    2. Check if the reverse is equal to original number
      • If yes : add to the sum (final result) 
  4. Redo Step 3.1 for all numbers in L and R
  5. Print the result and move to the next line
  6. Goto Step 3
  7. Exit 
Take care of the L and R constraints as they both have to be included in the calculation of the result.

SOLUTION : (Please use this as reference only)


Link to Code : Sum Of Palindromic Numbers
(Please Try To Refrain From Copying The Code)






No comments:

Post a Comment