my firstevery stackoverflow question so if I should've phrased it differently, please let me know.
I was doing this leetcode problem: 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.
Example 1:
Input: num1 = "11", num2 = "123" Output: "134"
I followed the solution pseudocode and wrote out pretty much the correct solution. However, it appears that the following lines are for some reason incorrect and I cannot figure out why.
Pseudocode: Set x1 to be equal to a digit from string nums1 at index p1. If p1 has reached the beginning of nums1, set x1 to 0.
Do the same for x2. Set x2 to be equal to digit from string nums2 at index p2. If p2 has reached the beginning of nums2, set x2 to 0.
My code:
if p1 <= 0:
x1 = 0
else:
x1 = ord(num1[p1])
if p2 <= 0:
x2 = 0
else:
x2 = ord(num2[p2])
Solution Code:
x1 = ord(num1[p1]) - ord('0') if p1 >= 0 else 0
x2 = ord(num2[p2]) - ord('0') if p2 >= 0 else 0
What is this python syntax? Why is it right while mine is not, as from what I can tell they accomplish the same thing.