Monday, April 22, 2019

Sum of palindromic numbers

  • Problem 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 palindromic numbers lying in the range [L, R], inclusive of both the extrema.

    Input
    The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.

    The first line of each test case contains a pair of space separated integers L and R denoting the range for which you are required to find the sum of the palindromic numbers.

    Output
    For each test case, output a single line containing the sum of all the palindromic numbers in the given range.

    Constraints
    1<=T<=100
    Subtask 1 (34 points) : 1<=L<=R<=103
    Subtask 2 (66 points) : 1<=L<=R<=105
    Explanation
    Example case 1. The palindromic numbers between 1 and 10 are all numbers except the number 10. Their sum is 45.
  • Test Case 1

    Input (stdin)
    2

    1 10

    123 150

    Expected Output
    sum is 45

    sum is 272
  • Test Case 2

    Input (stdin)
    5

    1 10

    12 30

    100 200

    50 60

    250 300

    Expected Output
    sum is 45

    sum is 22

    sum is 1460

    sum is 55

    sum is 1360
Solution

#define ull unsigned long long
#include <stdio.h>
#include <stdbool.h>
bool ispal(int n){
  int m=n,res=0;
  while(n){
    res*=10;
    res+=n%10;
    n/=10;
  }
  return res==m;
}
int main(){
  int t;
  scanf("%d",&t);
  while(t--){
    int i,min,max;
    ull res=0;
    scanf("%d%d",&min,&max);
    for(i=min;i<=max;i++){
      if(ispal(i)){
        res+=i;
      }
    }
    printf("sum is %lld\n",res);
  }
  return 0;
}

No comments:

Post a Comment

Parity

Problem Description Ram and Sita playing the parity game. Two types of parity are there. One is odd parity and next is even parity. Ram will...