0066. 加一 #18
Replies: 12 comments
-
看起来很简单,但我写起来的时候,思路感觉很不流畅 |
Beta Was this translation helpful? Give feedback.
-
进位我脑子就糊涂,所以我把digits组合成数字然后加一(比如[3,5,9]→359 + 1→360),就不用在算法里考虑进位了。然后用map函数将数字分开(360→[3,6,0])。 |
Beta Was this translation helpful? Give feedback.
-
嗯嗯,这种思路比较简单,代码写起来也比较容易。 不过,可以多加思考一下。Python 语言里的数字长度是没有限制的,而 C 语言、Java 中的 int 整型最大能存 2^31-1 的数字。题目中给出的数组长度最大为 100,显然超过了 int 能存储的范围,这就需要通过文中的方式,模拟进行加法运算了。 |
Beta Was this translation helpful? Give feedback.
-
直接用map 函数搞定! |
Beta Was this translation helpful? Give feedback.
-
这个方法更好些。
|
Beta Was this translation helpful? Give feedback.
-
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
ListLen = len(digits)
Jinwei = 1
if(digits[ListLen-1] + Jinwei== 10 ):
if(ListLen != 1):
for i in range (ListLen - 1 , -1 , -1):
if (digits[i] + Jinwei == 10):
digits[i] = 0
else :
digits[i] += Jinwei
Jinwei = 0
if(digits[0] == 0):
digits.insert(0,1)
else:
digits[0] = 0
digits.insert(0,1)
else:
digits[ListLen-1]=digits[ListLen-1]+1
return digits 暴力法 漏了好多 呜呜呜 |
Beta Was this translation helpful? Give feedback.
-
运用递归的也可以,而且个人觉得比较容易理解。 class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
last_digit = digits[-1]
if last_digit < 9:
digits[-1] = last_digit + 1
else:
if len(digits) == 1:
digits = [1, 0]
else:
digits = self.plusOne(digits[:-1]) + [0]
return digits |
Beta Was this translation helpful? Give feedback.
-
判断末尾是否为9,不是9直接加一#末尾是9,加一写为10,然后从最后一位开始从后往前迭代,每位如果是10就写为0,前一位加1,最后第零位单独处理 |
Beta Was this translation helpful? Give feedback.
-
class Solution(object): |
Beta Was this translation helpful? Give feedback.
-
直接判断当前位是否为9比较快点: |
Beta Was this translation helpful? Give feedback.
-
直接判断当前位是否为9
|
Beta Was this translation helpful? Give feedback.
-
0066. 加一 | 算法通关手册
解题思路 # 这道题把整个数组看成了一个整数,然后个位数 +1。问题的实质是利用数组模拟加法运算。
如果个位数不为 9 的话,直接把个位数 +1 就好。如果个位数为 9 的话,还要考虑进位。
具体步骤:
数组前补 0 位。 将个位数字进行 +1 计
https://algo.itcharge.cn/Solutions/0001-0099/plus-one
Beta Was this translation helpful? Give feedback.
All reactions