본문 바로가기

DataStructure/Array

Add One To Number

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.

  1. class Solution:
  2. 1.
  3. # @param A : list of integers
    
  4. # @return a list of integers
    
  5. def plusOne(self,A):
    
  6.     s = ''.join(map(str, A))
    
  7.     res = int(s)
    
  8.     res+=1
    
  9.     res = [int(x) for x in str(res)]
    
  10.     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