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.
Example:
If the vector has [1, 2, 3]
the returned vector should be [1, 2, 4]
as 123 + 1 = 124
.
NOTE: Certain things are intentionally left unclear in this question which you should practice asking the interviewer.
For example, for this problem, following are some good questions to ask :
- Q : Can the input have 0’s before the most significant digit. Or in other words, is
0 1 2 3
a valid input?A : For the purpose of this question, YES
- Q : Can the output have 0’s before the most significant digit? Or in other words, is
0 1 2 4
a valid output?- A : For the purpose of this question, NO. Even if the input has zeroes before the most significant digit.
My solution:
class Solution:
# @param A : list of integers
# @return a list of integers
def plusOne(self, A):
size = len(A)
results = list()
sum = 0
for i in range(size):
if i == 0 and A[i] == 0 and size > 1:
pass
# results.append(A[i])
if i > 0:
sum *= 10
sum += A[i]
if i == size - 1:
sum += 1
str_result = str(sum)
for i in range(len(str_result)):
results.append(int(str_result[i]))
return results
Good solutions:
Although you should not solve it this way as you should know the actual implementation
but this is an easier alternative for python guys.
- class Solution:
- 1.
# @param A : list of integers
# @return a list of integers
def plusOne(self,A):
s = ''.join(map(str, A))
res = int(s)
res+=1
res = [int(x) for x in str(res)]
return res
2. return str(int(''.join(map(str, A)))+1)
'DataStructure > Array' 카테고리의 다른 글
Maximum Absolute Difference (0) | 2018.10.17 |
---|---|
Max Sum Contiguous Subarray (0) | 2018.10.16 |
Min Steps in Infinite Grid (0) | 2018.10.15 |
Left Rotation (0) | 2018.04.19 |
Dynamic Array (0) | 2018.04.19 |