Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to add two numbers represented as strings in Python
Suppose we have two strings S and T, these two are representing integers. We have to add them and find the result in the same string representation.
So, if the input is like "256478921657", "5871257468", then the output will be "262350179125", as 256478921657 + 5871257468 = 262350179125.
Approach
To solve this, we will follow these steps ?
- Convert S and T from string to integer
- Add the integers: result = S + T
- Return the result as string
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, a, b):
return str(int(a) + int(b))
ob = Solution()
print(ob.solve("256478921657", "5871257468"))
The output of the above code is ?
262350179125
Alternative Approach
We can also solve this without using a class structure ?
def add_string_numbers(num1, num2):
return str(int(num1) + int(num2))
# Test with the example
result = add_string_numbers("256478921657", "5871257468")
print(f"Result: {result}")
print(f"Verification: {int('256478921657') + int('5871257468')}")
The output of the above code is ?
Result: 262350179125 Verification: 262350179125
How It Works
The solution works by leveraging Python's built-in type conversion functions:
-
int()converts string to integer -
str()converts integer back to string - Python handles large integers automatically without overflow
Conclusion
Adding string-represented numbers in Python is straightforward using type conversion. Convert strings to integers, perform addition, then convert back to string format for the final result.
