Sum of integer value of input Array and reverse Array
Last Updated :
13 Apr, 2023
Given an integer array of numbers num[], the task is to write a function to return the sum of the value of the array with its reverse value and then return the resulting array of digits.
Examples:
Input: num[] = [2, 5, 8, 2]
Output: [5, 4, 3, 4]
Explanation: Given array [2, 5, 8, 2], the numerical value is 2582 and the reverse value is 2852, so the sum is 2582 + 2852 = [5, 4, 3, 4]
Input: num[] = [2, 4, 6]
Output: [8, 8, 8]
Explanation: Given array [2, 4, 6] the numerical value is 246 and the reverse value is 642, so the sum is 246 + 642 = [8, 8, 8]
Approach: The approach for solving this problem is as follows:
- Convert the input integer array num[] into a single integer value num by concatenating all the elements of the array as strings and then converting the result into an integer.
- Reverse the input array number to get a new array reverse_number.
- Convert the reversed array reverse_number into a single integer value reverse_num using the same method as described in step 1.
- Find the sum of num and reverse_num and store it in a variable sum_num.
- Convert the value of sum_num into a list of individual digits and return it as the result.
Below is the implementation for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
std::vector<int> sum_of_array_and_its_reverse(const std::vector<int>& number)
{
int num = 0, mul = 1;
for (int i = number.size() - 1; i >= 0; i--) {
num += number[i] * mul;
mul *= 10;
}
int rev_num = 0, mul_rev = 1;
for (int i = 0; i < number.size(); i++) {
rev_num += number[i] * mul_rev;
mul_rev *= 10;
}
int result = num + rev_num;
std::vector<int> res;
while (result > 0) {
res.push_back(result % 10);
result /= 10;
}
std::reverse(res.begin(), res.end());
return res;
}
// Driver code
int main()
{
std::vector<int> number1 = { 2, 5, 8, 2 };
std::vector<int> result1 = sum_of_array_and_its_reverse(number1);
for (int i : result1) {
std::cout << i << " ";
}
std::cout << std::endl;
std::vector<int> number2 = { 5, 5, 5 };
std::vector<int> result2 = sum_of_array_and_its_reverse(number2);
for (int i : result2) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Main {
static List<Integer> sum_of_array_and_its_reverse(List<Integer> number)
{
int num = 0, mul = 1;
for (int i = number.size() - 1; i >= 0; i--) {
num += number.get(i) * mul;
mul *= 10;
}
int rev_num = 0, mul_rev = 1;
for (int i = 0; i < number.size(); i++) {
rev_num += number.get(i) * mul_rev;
mul_rev *= 10;
}
int result = num + rev_num;
List<Integer> res = new ArrayList<>();
while (result > 0) {
res.add(result % 10);
result /= 10;
}
Collections.reverse(res);
return res;
}
public static void main(String[] args)
{
List<Integer> number1 = new ArrayList<>();
number1.add(2);
number1.add(5);
number1.add(8);
number1.add(2);
List<Integer> result1 = sum_of_array_and_its_reverse(number1);
System.out.println(result1);
List<Integer> number2 = new ArrayList<>();
number2.add(2);
number2.add(4);
number2.add(6);
List<Integer> result2 = sum_of_array_and_its_reverse(number2);
System.out.println(result2);
}
}
Python3
def sum_of_array_and_its_reverse(number):
num = int("".join(str(x) for x in number))
rev_num = int("".join(str(x) for x in reversed(number)))
result = num + rev_num
return [int(x) for x in str(result)]
print(sum_of_array_and_its_reverse([2, 5, 8, 2])) # Output: [5, 4, 3, 4]
print(sum_of_array_and_its_reverse([2, 4, 6])) # Output: [8, 8, 8]
JavaScript
function sum_of_array_and_its_reverse(number) {
let num = 0, mul = 1;
for (let i = number.length - 1; i >= 0; i--) {
num += number[i] * mul;
mul *= 10;
}
let rev_num = 0, mul_rev = 1;
for (let i = 0; i < number.length; i++) {
rev_num += number[i] * mul_rev;
mul_rev *= 10;
}
let result = num + rev_num;
let res = [];
while (result > 0) {
res.push(result % 10);
result = Math.floor(result / 10);
}
res.reverse();
return res;
}
let number1 = [2, 5, 8, 2];
let result1 = sum_of_array_and_its_reverse(number1);
console.log(result1);
let number2 = [2, 4, 6];
let result2 = sum_of_array_and_its_reverse(number2);
console.log(result2);
C#
using System;
using System.Linq;
namespace SumOfArrayWithReverse {
class Program {
static void Main(string[] args)
{
int[] number = new int[] { 9, 9, 9 };
int[] result = SumArrayWithReverse(number);
Console.WriteLine("Result: " + string.Join(", ", result));
int[] number2 = new int[] { 5, 5, 5 };
int[] result2 = SumArrayWithReverse(number2);
Console.WriteLine("\nResult: " + string.Join(", ", result2));
}
static int[] SumArrayWithReverse(int[] number)
{
int[] reverseNumber = number.Reverse().ToArray();
int[] result = new int[number.Length];
int carry = 0;
for (int i = 0; i < number.Length; i++) {
int sum = number[i] + reverseNumber[i] + carry;
result[i] = sum % 10;
carry = sum / 10;
}
if (carry > 0) {
Array.Resize(ref result, result.Length + 1);
result[result.Length - 1] = carry;
}
return result.Reverse().ToArray();
}
}
}
Time complexity: O(n) where n is the length of the input array
This is because the code iterates through the input array twice, once to compute the original number and once to compute the reversed number. The size of the result vector is also proportional to the size of the input array, so iterating through the result vector has a time complexity of O(n) as well. Therefore, the overall time complexity of the function is O(n), which is linear with respect to the size of the input.
Auxiliary Space: O(n) where n is the size of the input vector.
This is because the code creates a new vector to store the digits of the result, which can also be of size n in the worst case.
Method: Numerical reverse-and-add approach
The numerical reverse-and-add approach involves the following steps:
- Convert the array to a numerical value: Iterate through the array and multiply each digit by its corresponding place value to obtain the numerical value of the array.
- Reverse the array: Reverse the array to obtain the reversed array.
- Convert the reversed array to a numerical value: Iterate through the reversed array and multiply each digit by its corresponding place value to obtain the numerical value of the reversed array.
- Add the two numerical values: Add the numerical values obtained in steps 1 and 3 to obtain the sum.
- Convert the sum to an array of digits: Repeatedly divide the sum by 10 and take the remainder to obtain each digit. Add each digit to the resulting array until the sum becomes 0. Reverse the resulting array to obtain the final array of digits.
This approach can be used to efficiently compute the sum of the value of an array with its reverse value.
C++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> reverse_sum(vector<int> num) {
// Convert the vector to a numerical value
int n = num.size();
int num_value = 0;
for (int i = 0; i < n; i++) {
num_value += num[i] * pow(10, n-i-1);
}
// Reverse the vector and obtain the numerical value of the reversed vector
vector<int> reverse_num(num.rbegin(), num.rend());
int reverse_value = 0;
for (int i = 0; i < n; i++) {
reverse_value += reverse_num[i] * pow(10, n-i-1);
}
// Add the two numerical values
int sum_value = num_value + reverse_value;
// Convert the sum to a vector of digits
vector<int> result;
while (sum_value > 0) {
result.insert(result.begin(), sum_value % 10);
sum_value /= 10;
}
return result;
}
int main() {
vector<int> num1 = {2, 5, 8, 2};
vector<int> num2 = {2, 4, 6};
vector<int> result1 = reverse_sum(num1);
vector<int> result2 = reverse_sum(num2);
// Print the results
for (int i = 0; i < result1.size(); i++) {
cout << result1[i]<<" ";
}
cout << endl;
for (int i = 0; i < result2.size(); i++) {
cout << result2[i]<<" ";
}
cout << endl;
return 0;
}
Java
/*package whatever //do not write package name here */
import java.util.*;
public class GFG {
public static List<Integer> reverse_sum(List<Integer> num) {
// Convert the list to a numerical value
int n = num.size();
int num_value = 0;
for (int i = 0; i < n; i++) {
num_value += num.get(i) * Math.pow(10, n-i-1);
}
// Reverse the list and obtain the numerical value of the reversed list
List<Integer> reverse_num = new ArrayList<>(num);
Collections.reverse(reverse_num);
int reverse_value = 0;
for (int i = 0; i < n; i++) {
reverse_value += reverse_num.get(i) * Math.pow(10, n-i-1);
}
// Add the two numerical values
int sum_value = num_value + reverse_value;
// Convert the sum to a list of digits
List<Integer> result = new ArrayList<>();
while (sum_value > 0) {
result.add(0, sum_value % 10);
sum_value /= 10;
}
return result;
}
public static void main(String[] args) {
List<Integer> num1 = new ArrayList<>(Arrays.asList(2, 5, 8, 2));
List<Integer> num2 = new ArrayList<>(Arrays.asList(2, 4, 6));
List<Integer> result1 = reverse_sum(num1);
List<Integer> result2 = reverse_sum(num2);
// Print the results
for (int i = 0; i < result1.size(); i++) {
System.out.print(result1.get(i) + " ");
}
System.out.println();
for (int i = 0; i < result2.size(); i++) {
System.out.print(result2.get(i) + " ");
}
System.out.println();
}
}
Python3
def reverse_sum(num):
# Convert the array to a numerical value
n = len(num)
num_value = 0
for i in range(n):
num_value += num[i] * 10**(n-i-1)
# Reverse the array and obtain the numerical value of the reversed array
reverse_num = num[::-1]
reverse_value = 0
for i in range(n):
reverse_value += reverse_num[i] * 10**(n-i-1)
# Add the two numerical values
sum_value = num_value + reverse_value
# Convert the sum to an array of digits
result = []
while sum_value > 0:
result.append(sum_value % 10)
sum_value //= 10
return result[::-1]
print(reverse_sum([2, 5, 8, 2]))
# Output: [5, 4, 3, 4]
print(reverse_sum([2, 4, 6]))
# Output: [8, 8, 8]
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
// Function to reverse the sum
static List<int> ReverseSum(List<int> num)
{
// Convert the list to numerical value
int n = num.Count;
int numValue = 0;
for (int i = 0; i < n; i++) {
numValue
+= num[i] * (int)Math.Pow(10, n - i - 1);
}
// Reverse the list and obtain the
// numerical value of the reversed list
List<int> reverseNum = num.ToList();
reverseNum.Reverse();
int reverseValue = 0;
for (int i = 0; i < n; i++) {
reverseValue += reverseNum[i]
* (int)Math.Pow(10, n - i - 1);
}
// Add the two numerical values
int sumValue = numValue + reverseValue;
// Convert the sum to a list of digits
List<int> result = new List<int>();
while (sumValue > 0) {
result.Insert(0, sumValue % 10);
sumValue /= 10;
}
return result;
}
// Driver Code
static void Main(string[] args)
{
List<int> num1 = new List<int>{ 2, 5, 8, 2 };
List<int> num2 = new List<int>{ 2, 4, 6 };
List<int> result1 = ReverseSum(num1);
List<int> result2 = ReverseSum(num2);
// Print the results
foreach(int num in result1)
{
Console.Write(num + " ");
}
Console.WriteLine();
foreach(int num in result2)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
JavaScript
function reverseSum(num) {
// Convert the array to numerical value
let n = num.length;
let numValue = 0;
for (let i = 0; i < n; i++) {
numValue += num[i] * Math.pow(10, n - i - 1);
}
// Reverse the array and obtain the
// numerical value of the reversed array
let reverseNum = [...num].reverse();
let reverseValue = 0;
for (let i = 0; i < n; i++) {
reverseValue += reverseNum[i] * Math.pow(10, n - i - 1);
}
// Add the two numerical values
let sumValue = numValue + reverseValue;
// Convert the sum to an array of digits
let result = [];
while (sumValue > 0) {
result.unshift(sumValue % 10);
sumValue = Math.floor(sumValue / 10);
}
return result;
}
// Driver Code
let num1 = [2, 5, 8, 2];
let num2 = [2, 4, 6];
let result1 = reverseSum(num1);
let result2 = reverseSum(num2);
// Print the results
console.log(result1.join(' '));
console.log(result2.join(' '));
Output[5, 4, 3, 4]
[8, 8, 8]
The time complexity of this approach is O(n), where n is the length of the input array.
The space complexity is also O(n), as we need to store the reversed array and the resulting array of digits.
Similar Reads
Sum of f(a[i], a[j]) over all pairs in an array of n integers
Given an array of n integers, find the sum of f(a[i], a[j]) of all pairs (i, j) such that (1 <= i < j <= n). f(a[i], a[j]): If |a[j]-a[i]| > 1 f(a[i], a[j]) = a[j] - a[i] Else // if |a[j]-a[i]| <= 1 f(a[i], a[j]) = 0 Examples: Input : 6 6 4 4 Output : -8 Explanation: All pairs are: (6
8 min read
Find if array has an element whose value is half of array sum
Given a sorted array (with unique entries), we have to find whether there exists an element(say X) that is exactly half the sum of all the elements of the array including X. Examples: Input : A = {1, 2, 3} Output : YES Sum of all the elements is 6 = 3*2; Input : A = {2, 4} Output : NO Sum of all the
10 min read
Sum of an array of large numbers
Given an integer K and an array arr[] consisting of N large numbers in the form of strings, the task is to find the sum of all the large numbers of the array. Examples: Input: K = 50, arr[] = {â01234567890123456789012345678901234567890123456789â, â01234567890123456789012345678901234567890123456789â,
10 min read
Print the sum of array after doing k queries on the array
Given an array, arr[] of size n. Calculate the sum of arr[] by performing k queries on arr[], such that we have to add an element given in array y[], on the basis of the boolean value given in array check[]. For every index i (0<= i <= n - 1): If check[i] = true, Add y[i] to all the odd number
10 min read
Sum of Bitwise OR of every array element paired with all other array elements
Given an array arr[] consisting of non-negative integers, the task for each array element arr[i] is to print the sum of Bitwise OR of all pairs (arr[i], arr[j]) ( 0 ⤠j ⤠N ). Examples: Input: arr[] = {1, 2, 3, 4}Output: 12 14 16 22Explanation:For i = 0 the required sum will be (1 | 1) + (1 | 2) + (
11 min read
Sum of all palindrome numbers present in an Array
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(rever
11 min read
Replace every element of the array by sum of all other elements
Given an array of size N, the task is to find the encrypted array. The encrypted array is obtained by replacing each element of the original array with the sum of the remaining array elements i.e. For every i, arr[i] = sumOfArrayElements - arr[i] Examples: Input: arr[] = {5, 1, 3, 2, 4} Output: 10 1
5 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the val
4 min read
Sum of Bitwise And of all pairs in a given array
Given an array "arr[0..n-1]" of integers, calculate sum of "arr[i] & arr[j]" for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples : Input: arr[] = {5, 10, 15} Output: 15 Required Value = (5 & 10) + (5 & 15) + (10
13 min read
Minimize the sum of MEX by removing all elements of array
Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
7 min read