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.
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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Write a program to calculate pow(x,n)
- Write a program to reverse digits of a number
- Program to find whether a no is power of two
- Program to find parity
- Write an Efficient C Program to Reverse Bits of a Number
- Write a program to print all permutations of a given string
- Write a program to add two numbers in base 14
- Multiply two integers without using multiplication, division and bitwise operators, and no loops
- Program for Fibonacci numbers
- Median in a stream of integers (running integers)
- Program to find amount of water in a given glass
- Program to convert a given number to words
- Efficient program to calculate e^x
- Efficient program to print all prime factors of a given number
- Program for nth Catalan Number
- Program for Rank of Matrix
- Find a pair with maximum product in array of Integers
- Program for Bisection Method
- Program for Newton Raphson Method
- Convert from any base to decimal and vice versa
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.