Python program to add two Octal numbers
Given two octal numbers, the task is to write a Python program to compute their sum.
Examples:
Input: a = "123", b = "456" Output: 601 Input: a = "654", b = "321" Output: 1175
Approach:
To add two octal values in python we will first convert them into decimal values then add them and then finally again convert them to an octal value. To convert the numbers we will make use of the oct() function. The oct() function is one of the built-in methods in Python3. The oct() method takes an integer and returns its octal representation in a string format. We will also use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal.
Below are the implementations based on the above explanation:
Example 1:
Python3
# Python program to add two hexadecimal numbers. # Driver code # Declaring the variables a = "123" b = "456" # Calculating octal value using function sum = oct ( int (a, 8 ) + int (b, 8 )) # Printing result print ( sum [ 2 :]) |
601
Example 2:
Python3
# Python program to add two hexadecimal numbers. # Driver code # Declaring the variables a = "654" b = "321" # Calculating octal value using function sum = oct ( int (a, 8 ) + int (b, 8 )) # Printing result print ( sum [ 2 :]) |
1175
Example 3:
Python3
# Python program to add two octal numbers. # Driver code if __name__ = = "__main__" : # Declaring the variables a = "654" b = "321" # Calculating octal sum by using hex() and int() octal_sum = lambda a,b : oct ( int (a, 8 ) + int (b, 8 )) # calling octal lambda function print (octal_sum(a,b)[ 2 :]) # This code is contributed by AnkThon |
1175
Time Complexity : O(1)
Space Complexity : O(1)
Method: Using “add” operator
Python3
from operator import * num1 = "654" num2 = "321" print ( oct (add( int (num1, 8 ), int (num2, 8 )))) |
Output
0o1175
Time Complexity : O(1)
Space Complexity : O(1)
Contact Us