Sum of all palindrome numbers present in an Array
Last Updated :
11 Jul, 2025
Given an array arr[] of N positive integers. The task is to find the sum of all palindrome numbers present in the array. Print the total sum.
A palindrome number is a number that when reversed is equal to the initial number. Example: 121 is palindrome(reverse(121) = 121), 123 is not palindrome(reverse(123) = 321).
Note: Consider palindrome numbers of length greater than 1 while calculating the sum.
Examples:
Input : arr[] ={12, 313, 11, 44, 9, 1}
Output : 368
Input : arr[] = {12, 11, 121}
Output : 132
Approach: The idea is to implement a reverse function that reverses a number from the right to left. Implement a function that checks for palindrome numbers and finally traverses the array and calculates the sum of all elements which are palindrome.
Below is the implementation of the above approach:
C++
// C++ program to calculate the sum of all
// palindromic numbers in array
#include<bits/stdc++.h>
using namespace std;
// Function to reverse a number n
int reverse(int n)
{
int d = 0, s = 0;
while (n > 0)
{
d = n % 10;
s = s * 10 + d;
n = n / 10;
}
return s;
}
// Function to check if a number n is
// palindrome
bool isPalin(int n)
{
// If n is equal to the reverse of n
// it is a palindrome
return n == reverse(n);
}
// Function to calculate sum of all array
// elements which are palindrome
int sumOfArray(int arr[], int n)
{
int s = 0;
for (int i = 0; i < n; i++)
{
if ((arr[i] > 10) && isPalin(arr[i]))
{
// summation of all palindrome numbers
// present in array
s += arr[i];
}
}
return s;
}
// Driver Code
int main()
{
int n = 6;
int arr[] = { 12, 313, 11, 44, 9, 1 };
cout << sumOfArray(arr, n);
return 0;
}
// This code is contributed by mits
Java
// Java program to calculate the sum of all
// palindromic numbers in array
class GFG {
// Function to reverse a number n
static int reverse(int n)
{
int d = 0, s = 0;
while (n > 0) {
d = n % 10;
s = s * 10 + d;
n = n / 10;
}
return s;
}
// Function to check if a number n is
// palindrome
static boolean isPalin(int n)
{
// If n is equal to the reverse of n
// it is a palindrome
return n == reverse(n);
}
// Function to calculate sum of all array
// elements which are palindrome
static int sumOfArray(int[] arr, int n)
{
int s = 0;
for (int i = 0; i < n; i++) {
if ((arr[i] > 10) && isPalin(arr[i])) {
// summation of all palindrome numbers
// present in array
s += arr[i];
}
}
return s;
}
// Driver Code
public static void main(String[] args)
{
int n = 6;
int[] arr = { 12, 313, 11, 44, 9, 1 };
System.out.println(sumOfArray(arr, n));
}
}
C#
// C# program to calculate the sum of all
// palindromic numbers in array
using System;
class GFG
{
// Function to reverse a number n
static int reverse(int n)
{
int d = 0, s = 0;
while (n > 0)
{
d = n % 10;
s = s * 10 + d;
n = n / 10;
}
return s;
}
// Function to check if a number n is
// palindrome
static bool isPalin(int n)
{
// If n is equal to the reverse of n
// it is a palindrome
return n == reverse(n);
}
// Function to calculate sum of all array
// elements which are palindrome
static int sumOfArray(int[] arr, int n)
{
int s = 0;
for (int i = 0; i < n; i++)
{
if ((arr[i] > 10) && isPalin(arr[i]))
{
// summation of all palindrome numbers
// present in array
s += arr[i];
}
}
return s;
}
// Driver Code
public static void Main(String[] args)
{
int n = 6;
int[] arr = { 12, 313, 11, 44, 9, 1 };
Console.WriteLine(sumOfArray(arr, n));
}
}
/* This code contributed by PrinciRaj1992 */
Python3
# Python3 program to calculate the sum of all
# palindromic numbers in array
# Function to reverse a number n
def reverse(n) :
d = 0; s = 0;
while (n > 0) :
d = n % 10;
s = s * 10 + d;
n = n // 10;
return s;
# Function to check if a number n is
# palindrome
def isPalin(n) :
# If n is equal to the reverse of n
# it is a palindrome
return n == reverse(n);
# Function to calculate sum of all array
# elements which are palindrome
def sumOfArray(arr, n) :
s = 0;
for i in range(n) :
if ((arr[i] > 10) and isPalin(arr[i])) :
# summation of all palindrome numbers
# present in array
s += arr[i];
return s;
# Driver Code
if __name__ == "__main__" :
n = 6;
arr = [ 12, 313, 11, 44, 9, 1 ];
print(sumOfArray(arr, n));
# This code is contributed by AnkitRai01
JavaScript
<script>
// Javascript program to calculate the
// sum of all palindromic numbers in array
// Function to reverse a number n
function reverse( n)
{
let d = 0, s = 0;
while (n > 0)
{
d = n % 10;
s = s * 10 + d;
n = Math.floor(n / 10);
}
return s;
}
// Function to check if a number n is
// palindrome
function isPalin(n)
{
// If n is equal to the reverse of n
// it is a palindrome
return n == reverse(n);
}
// Function to calculate sum of all array
// elements which are palindrome
function sumOfArray( arr, n)
{
let s = 0;
for(let i = 0; i < n; i++)
{
if ((arr[i] > 10) && isPalin(arr[i]))
{
// Summation of all palindrome
// numbers present in array
s += arr[i];
}
}
return s;
}
// Driver Code
let n = 6;
let arr = [ 12, 313, 11, 44, 9, 1 ];
document.write(sumOfArray(arr, n));
// This code is contributed by jana_sayantan
</script>
Time Complexity: O(n * max(arr)), where max(arr) is the largest element of the array arr.
Auxiliary Space: O(1), since no extra space has been taken.
Another approach :
In java, we can easily implement it by using StringBuilder object and the reverse() method.
Step 1: Get the input from the user
Step 2: Initialize sum=0 and iterate through each element.
Step 3: Now, convert the integer element to string by using Integer.toString(array[i])
Step 4:Reverse it by StringBuilder object using reverse() method and toString() is used to convert the object to string.
Step 5: Equalize both the string values and check element greater than 9. If it satisfies the condition, sum the elements.
C++
#include <bits/stdc++.h>
using namespace std;
string reverse(string str,int l,int r)
{
while(l<r)
{
swap(str[l++],str[r--]);
}
return str;
}
int main()
{
int array[]={12, 313, 11, 44, 9, 1};
int n = sizeof(array)/sizeof(array[0]);
int sum = 0;
for(int i = 0; i < n; i++){
string str = to_string(array[i]);
string rev=reverse(str,0,str.size()-1);
if(str == rev && array[i] > 9){
sum=sum+array[i];
}
}
cout << sum;
return 0;
}
// this code is contributed by aditya942003patil
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main (String[] args) {
int array[]={12, 313, 11, 44, 9, 1};
int n=array.length;
int sum=0;
for(int i=0;i<n;i++){
String str=Integer.toString(array[i]);
String rev=new StringBuilder(str).reverse().toString();
if(str.equals(rev) && array[i]>9){
sum=sum+array[i];
}
}
System.out.println(sum);
}
}
Python3
# Python3 program to implement the approach
# This method reverses the characters in a string
# in the range [l, r] by swapping characters
# from each end one by one
def reverse(str_, l, r):
str_ = list(str_)
while l < r:
str_[i], str_[j] = str_[j], str_[i]
l += 1
r -= 1
return "".join(str_)
# Driver Code
array = [12, 313, 11, 44, 9, 1]
n = len(array)
sum = 0
for i in range(n):
string = str(array[i])
rev = string[::-1]
if string == rev and array[i] > 9:
sum += array[i]
print(sum)
# This code is contributed by phasing17
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG {
// Function to reverse the string
static string reverse(string str)
{
// Convert string to char array
char[] charArray = str.ToCharArray();
// Char array to store reversed array
char[] result = new char[charArray.Length];
for (int i = 0, j = str.Length - 1; i < str.Length;
i++, j--) {
result[i] = charArray[j];
}
return new string(result);
}
public static void Main(string[] args)
{
int[] array = { 12, 313, 11, 44, 9, 1 };
int n = array.Length;
int sum = 0;
for (int i = 0; i < n; i++) {
// Convert to string
string str = Convert.ToString(array[i]);
// Reverse the string
string rev = reverse(str);
// If string is palindromic
// Update sum
if (str.Equals(rev) && array[i] > 9) {
sum = sum + array[i];
}
}
// Display result
Console.WriteLine(sum);
}
}
// This code is contributed by phasing17
JavaScript
// JavaScript code to implement the approach
function reverse(str, l, r)
{
str = str.split("");
while (l < r) {
let temp = str[r];
str[r--] = str[l];
str[l++] = temp;
}
return str.join("");
}
let array = [ 12, 313, 11, 44, 9, 1 ];
let n = array.length;
let sum = 0;
for (let i = 0; i < n; i++) {
let str = "" + (array[i]);
let rev = reverse(str, 0, str.length - 1);
if (str == rev && array[i] > 9) {
sum = sum + array[i];
}
}
console.log(sum);
// this code is contributed by phasing17
Time Complexity: O(n), where n is the size of the given array.
Auxiliary Space: O(d), where d is the maximum digits in number in the given array.
In python, we can execute it by implementing the below approach.
Step 1 : Initialize the list or array and sum=0.
Step 2 : Iterate the list using for loop and convert the integer element to string using str().
Step 3 : Reverse the string using string_element[ : : -1].
Step 4 :Equalize both the string values and check element greater than 9. If it satisfies the condition, sum the elements.
C++
// C++ program to implement the approach
#include <bits/stdc++.h>
using namespace std;
int main()
{
int lis[] = {12, 313, 11, 44, 9, 1};
int sum = 0;
for (int i : lis)
{
string string_conversion = to_string(i);
string rev_string = "" + string_conversion;
reverse(rev_string.begin(), rev_string.end());
if(string_conversion == (rev_string) && i>9)
sum = sum + i;
}
cout << sum;
}
// This code is contributed by phasing17
Java
// Java program to implement the approach
import java.util.*;
class GFG {
public static void main(String[] args)
{
int lis[] = { 12, 313, 11, 44, 9, 1 };
int sum = 0;
for (int i : lis) {
String string_conversion = String.valueOf(i);
StringBuilder rev
= new StringBuilder(string_conversion);
rev.reverse();
String rev_string = rev.toString();
if (string_conversion.equals(rev_string)
&& i > 9)
sum = sum + i;
}
System.out.println(sum);
}
}
// This code is contributed by phasing17
Python3
# code
lis=[12, 313, 11, 44, 9, 1]
sum=0;
for i in lis:
string_conversion=str(i)
rev_string=string_conversion[ : : -1]
if(string_conversion==rev_string and i>9):
sum=sum+i
print(sum)
C#
// C# program to implement the approach
using System;
using System.Collections.Generic;
class GFG {
public static void Main(string[] args)
{
int[] lis = { 12, 313, 11, 44, 9, 1 };
int sum = 0;
foreach(int i in lis)
{
string string_conversion = Convert.ToString(i);
char[] rev = string_conversion.ToCharArray();
Array.Reverse(rev);
string rev_string = new string(rev);
if (string_conversion.Equals(rev_string)
&& i > 9)
sum = sum + i;
}
Console.WriteLine(sum);
}
}
// This code is contributed by phasing17
JavaScript
// JS program to implement the approach
let lis = [12, 313, 11, 44, 9, 1]
let sum = 0;
for (var i of lis)
{
let string_conversion = "" + i
let rev_string = string_conversion.split("").reverse().join("");
if((string_conversion.localeCompare(rev_string) == 0) && i>9)
sum = sum + i
}
console.log(sum)
// This code is contributed by phasing17
Time Complexity: O(n)
Auxiliary Space: O(d), where d is the maximum digits in the number.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem