VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-add-two-integers-of-given-base/

⇱ Program to add two integers of given base - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to add two integers of given base

Last Updated : 3 Oct, 2022

Given three integers X, Y, and B, where X and Y are Base-B integers. The task is to find the sum of integers X and Y.

Examples: 

Input: X = 123, Y = 234, B = 6
Output: 401
Explanation:
Sum of two integers in base 6 - 
 1 1 
 1 2 3
+ 2 3 4
-------------
 4 0 1

Input: X = 546, Y = 248 B = 9
Output: 805
Explanation:
Sum of two integers in base 9 - 
 1 1
 5 4 6
+ 2 4 8
-------------
 8 0 5 

Approach: The idea is to use the fact that whenever two digits of the numbers are added, then the place value will be the modulo of the sum of digits by the base whereas carry will be the integer division of the sum of digits by base. i.e.  

Let two digits of the number be D1 and D2 -
Place Value = (D1 + D2) % B

Carry = (D1 + D2) / B

Similarly, Add every digit from the last to get the desired result.

Below is the implementation of the above approach: 


Output
401

Time Complexity: O(max(len_a , len_b))
Auxiliary Space: O(max(len_a , len_b))

Comment
Article Tags:
Article Tags: