{ "question_id": 66, "question_title": "加一", "difficulty": "简单", "question_content": "

给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

 

示例 1:

输入:digits = [1,2,3]
输出:
[1,2,4]
解释:
输入数组表示数字 123。

示例 2:

输入:digits = [4,3,2,1]
输出:
[4,3,2,2]
解释:
输入数组表示数字 4321。

示例 3:

输入:digits = [0]
输出:
[1]

 

提示:

", "topic_link": "https://bbs.csdn.net/topics/600469823", "cpp": "#include \nusing namespace std;\nclass Solution\n{\npublic:\n\tvector plusOne(vector &digits)\n\t{\n\t\tint carry = 1;\n\t\tvector res;\n\t\tfor (int i = digits.size() - 1; i >= 0; i--)\n\t\t{\n\t\t\tint d = digits[i] + carry;\n\t\t\tres.push_back(d % 10);\n\t\t\tcarry = d / 10;\n\t\t}\n\t\tif (carry > 0)\n\t\t{\n\t\t\tres.push_back(carry);\n\t\t}\n\t\treverse(res.begin(), res.end());\n\t\treturn res;\n\t}\n};", "java": "class Solution {\n\tpublic int[] plusOne(int[] digits) {\n\t\tint i = digits.length - 1;\n\t\twhile (i >= 0 && (digits[i] = digits[i] + 1) == 10) {\n\t\t\tdigits[i] = 0;\n\t\t\ti--;\n\t\t}\n\t\tif (digits[0] == 0) {\n\t\t\tint[] temp = new int[digits.length + 1];\n\t\t\ttemp[0] = 1;\n\t\t\treturn temp;\n\t\t}\n\t\treturn digits;\n\t}\n}", "js": "", "python": "class Solution(object):\n\tdef plusOne(self, digits):\n\t\tls = len(digits)\n\t\tfor index in reversed(range(ls)):\n\t\t\tif digits[index] < 9:\n\t\t\t\tdigits[index] += 1\n\t\t\t\treturn digits\n\t\t\telse:\n\t\t\t\tdigits[index] = 0\n\t\tdigits.insert(0, 1)\n\t\treturn digits\n# %%\ns = Solution()\nprint(s.plusOne(digits = [1,2,3]))", "status": 1, "keywords": "数组,数学", "license": { "cpp": "https://github.com/begeekmyfriend/leetcode", "python": "https://github.com/qiyuangong/leetcode", "java": "https://github.com/zhangyu345293721/leetcode" }, "notebook": { "cpp": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/65/65_cpp.ipynb?type=file", "python": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/65/65_python.ipynb?type=file", "java": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/65/65_java.ipynb?type=file" }, "notebook_enable": 1 }