# The Plus One problem solved with Python

## The challenge

Given a non-empty array of digits representing a non-negative integer, increment one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

```Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.```

Example 2:

```Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.```

## The solution in Python

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```def plusOne(self, digits: List[int]) -> List[int]:
# check that digits exists and is bigger than 0
if len(digits)==0:
# fail safe
return digits
else:
# increment the number to a single integer
number = int(''.join([str(k) for k in digits]))+1
# return back a list representation
return [int(k) for k in str(number)]
```Code language: Python (python)```
Tags:
Subscribe
Notify of
1 Comment
Inline Feedbacks