Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Given a non-negative number represented as an array of digits,
- add 1 to the number ( increment the number represented by the digits ).
- The digits are stored such that the most significant digit is at the head of the list. There can be upto 10,000 digits in the input array.
- Example:
- If the vector has [1, 2, 3]
- the returned vector should be [1, 2, 4]
- as 123 + 1 = 124.
- def plusOne(a)
- new_number = a.join.to_i + 1
- result = []
- while new_number > 0
- result.push new_number%10
- new_number /= 10
- end
- result.reverse
- end
- def plusOne(a)
- carry = 1
- start_index = a.size - 1
- temp_result = []
- ans = []
- for i in start_index.downto(0)
- sum = a[i] + carry
- carry = sum/10
- temp_result.push sum%10
- end
- temp_result.push carry
- start_index = temp_result.size - 1
- while start_index >= 0 and temp_result[start_index] == 0
- start_index -= 1
- end
- while start_index >= 0
- ans.push temp_result[start_index]
- start_index -= 1
- end
- ans
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement