File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Python/Interviewbit/Arrays Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Problem Link: https://www.interviewbit.com/problems/add-one-to-number/
3
+
4
+ Given a non-negative number represented as an array of digits,
5
+ add 1 to the number ( increment the number represented by the digits ).
6
+ The digits are stored such that the most significant digit is at the head of the list.
7
+
8
+ Example:
9
+ If the vector has [1, 2, 3]
10
+ the returned vector should be [1, 2, 4]
11
+ as 123 + 1 = 124.
12
+
13
+ NOTE: Certain things are intentionally left unclear in this question which you should practice
14
+ asking the interviewer.
15
+ For example, for this problem, following are some good questions to ask :
16
+ Q : Can the input have 0’s before the most significant digit. Or in other words, is 0 1 2 3 a
17
+ valid input?
18
+ A : For the purpose of this question, YES
19
+ Q : Can the output have 0’s before the most significant digit? Or in other words, is 0 1 2 4
20
+ a valid output?
21
+ A : For the purpose of this question, NO. Even if the input has zeroes before the most significant
22
+ digit.
23
+ """
24
+ class Solution :
25
+ # @param A : list of integers
26
+ # @return a list of integers
27
+ def plusOne (self , A ):
28
+ rem = 0
29
+ carry = 1
30
+ i = len (A ) - 1
31
+ while i >= 0 :
32
+ if A [i ] < 9 :
33
+ A [i ] += 1
34
+ carry = 0
35
+ break
36
+ else :
37
+ A [i ] = 0
38
+ i -= 1
39
+
40
+ if carry :
41
+ A .insert (0 , 1 )
42
+ i = 0
43
+ while i < len (A ) and A [i ] == 0 :
44
+ i += 1
45
+
46
+ return A [i :]
You can’t perform that action at this time.
0 commit comments