Skip to content

Commit 31b6f9e

Browse files
committed
Add One To Number
1 parent 42b3afb commit 31b6f9e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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:]

0 commit comments

Comments
 (0)