
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Sum of two large numbers in C++
In this problem, we are given two string that defines two large numbers. Our task is to create a program to find the sum of two large numbers.
Let’s take an example to understand the problem,
Input: number1 = “341299123919” number2 = “52413424” Output: 341351537343
To solve this problem, we will traverse both the string. And add digit by digit and propagate the carry. And store the result digit by digit to sum string.
Algorithm
Initialize sum = 0, carry = 0. Step 1: loop from n to 0. Step 1.1: intSum = number1[i] + number2[i] Step 1.2: carry = intSum/10. Sum += intSum Step 2: sum += carry. Step 3: return sum.
Example
Program to illustrate the working of our solution,
#include<bits/stdc++.h> using namespace std; string addBigNumbers(string number1, string number2) { if (number1.length() > number2.length()) swap(number1, number2); string sum = ""; int len1 = number1.length(); int len2 = number2.length(); int digitDiff = len2 - len1; int carry = 0; int intSum; for (int i=len1-1; i>=0; i--) { intSum = ((number1[i]-'0') + (number2[i+digitDiff]- '0') + carry); sum.push_back(intSum%10 + '0'); carry = intSum/10; } for (int i=digitDiff-1; i>=0; i--) { intSum = ((number2[i]-'0')+carry); sum.push_back(intSum%10 + '0'); carry = intSum/10; } if (carry) sum.push_back(carry+'0'); reverse(sum.begin(), sum.end()); return sum; } int main() { string number1 = "235235823852"; string number2 = "45230820348"; cout<<"Sum of two large numbers is "<<addBigNumbers(number1,x number2); return 0; }
Output
Sum of two large numbers is 280466644200
- Related Articles
- Sum of two numbers modulo M in C++
- Large Fibonacci Numbers in C#
- Handling large numbers in C++?
- Sum of the multiples of two numbers below N in C++
- C program to find sum and difference of two numbers
- Minimum sum of two numbers formed from digits of an array in C++
- C++ Program to Find Factorial of Large Numbers
- Sum of Square Numbers in C++
- How to find the Sum of two Binary Numbers using C#?
- Multiply Large Numbers represented as Strings in C++
- Find the Sum of two Binary Numbers without using a method in C#?
- Print all integers that are sum of powers of two given numbers in C++
- Sum of sum of first n natural numbers in C++
- Find two numbers whose sum and GCD are given in C++
- Check if a large number can be divided into two or more segments of equal sum in C++

Advertisements