Given an integer `n`

, return the sum of the first `n`

palindromes.

1 <= n <= 10000 , where

`n`

is the integer.

A **palindrome** is a word, number, phrase, or sequence of characters that reads the same backward as it does forward (e.g., madam, racecar, 909, etc.)

**Input :**

5

**Output :**

15

**Explanation**

The sum of the first 5 palindromes (1, 2, 3, 4, 5) is 15.

First, we input the value of `n`

using the `input()`

function.
Then, we initialize the variables `sum`

and `count`

to 0.

sum=0

count=0

Next, we enter the for loop where we can iterate the loop for any number of times. However, in this case, we will use it till 10,000, but you can change the end value to any number you wish.

for i in range(1,10000) :

Once inside the loop, the first step is to convert the number to a string, i.e., reverse the string using `[::-1]`

.
Next, we compare the reversed number to the actual number and, if they are the same, we can calculate the sum by:

sum=sum+1

Then, we count the number of times the actual number is reversed using:

count=count+1

Once the count has reached the `n`

value, we use `break`

to terminate the loop.

We then print the sum of `n`

palindromes in the next line.

The code is given below:

n=int(5)count=0sum=0for i in range(1,10000) :x=str(i) #changes i to stry=x[::-1] #reverses the numberif x==y :sum =sum+icount=count+1if count==n :breakprint("sum=" ,sum) #prints the sum

The program uses integer `n`

, which takes `O(1)`

. But, the complexity of the result, that is the size of “sum from 1 to `n`

," is `n(n – 1) / 2 is O(n ^ 2)`

.

TRENDING TOPICS