diff --git a/algorithms/Go/README.md b/algorithms/Go/README.md index 62f93ab9..0e12c10e 100644 --- a/algorithms/Go/README.md +++ b/algorithms/Go/README.md @@ -7,6 +7,7 @@ - [Contains Duplicate](arrays/contains_duplicate.go) - [Single Number](arrays/single-number.go) + ## Scheduling - [Interval Scheduling](scheduling/interval-scheduling.go) @@ -25,3 +26,4 @@ ## String - [Palindrome Permutation](strings/palindrome-permutation.go) + diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 3095ee25..1b8365cc 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -48,6 +48,7 @@ - [First Non Repeating Character](strings/first_non_repeating_character.py) - [Longest Common Subsequence](strings/longest_common_subsequence.py) - [Unique Character](strings/unique_character.py) +- [Add String](strings/add_string.py) ## Dynamic Programming - [Print Fibonacci Series Up To N-th Term](dynamic_programming/fibonacci_series.py) @@ -56,9 +57,6 @@ - [Catalan Sequence](dynamic_programming/catalan_sequence.py) - [0/1 Knapsack Problem](dynamic_programming/knapsack.py) -## Trees -- [Binary Tree](trees/binary_tree.py) - ## Graphs - [Simple Graph](graphs/graph.py) diff --git a/algorithms/Python/strings/add_string.py b/algorithms/Python/strings/add_string.py new file mode 100644 index 00000000..0bf0d46b --- /dev/null +++ b/algorithms/Python/strings/add_string.py @@ -0,0 +1,42 @@ +""" +Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. + +You must solve the problem without using any built-in library for handling large integers (such as BigInteger). + +You must also not convert the inputs to integers directly. + +Time: O(max(len(num1), len(num2))) +Space: O(max(len(num1), len(num2)) + 1) + +Key points: Traverse reversely of both strings +""" + +def add_string(num1, num2): + carry = 0 + ptr1, ptr2 = len(num1) - 1, len(num2) - 1 + result = "" + + while ptr1 >= 0 or ptr2 >= 0 or carry: + if ptr1 >= 0: + carry += (ord(num1[ptr1]) - ord("0")) + ptr1 -= 1 + if ptr2 >= 0: + carry += (ord(num2[ptr2]) - ord('0')) + ptr2 -= 1 + + result = str(carry % 10) + result + carry //= 10 + return result + + +if __name__ == "__main__": + num1 = "11" + num2 = "123" + result = add_string(num1, num2) #expected result "134" + + print("First test: ",result) + + num1 = "456" + num2 = "77" + result = add_string(num1, num2) #expected result "533" + print("Second test: ",result) \ No newline at end of file