leetcode66题 题解 翻译 C语言版 Python版
来源:互联网 发布:线切割编程 编辑:程序博客网 时间:2024/06/07 12:12
66. Plus One
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
66.加一
给定一个由数字数组表示的非负整数,给它加上一。
数字存储方式是表头为高位。
思路:对于c这样需要分配好数组大小的语言来说,如果整个数加1后最高位没有进位,那么可以分配与原数组长度一致的新数组,但如果最高位有进位时,数组长度就要加1。最高位有进位当且仅当当前的所有位都为9时,所以最开始可以遍历一遍数组,只要有一个不为9,那么就和原数组长度一致。进位操作很简单,从数组最后一位开始遍历,大于9就进位,小于9不进位。
如果是python等操作数组较方便的语言,可以最后时再在数组前面插入一个元素。注意用python时没有要求分配新的list,只需要修改原来传入的list即可,但最后要返回
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* plusOne(int* digits, int digitsSize, int* returnSize) { int carry = 1; for (int i = 0; i < digitsSize; i++){ if (digits[i] != 9){ carry = 0; break; } } int* plusone = (int*)malloc(sizeof(int)*(digitsSize+carry)); if (carry){ plusone[0] = 1; } int p = 1; for (int i = digitsSize - 1; i >= 0; i--){ plusone[i+carry] = digits[i] + p; if (plusone[i+carry] > 9){ plusone[i+carry] -= 10; p = 1; } else{ p = 0; } } *returnSize = digitsSize+carry; return plusone;}
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ carry = 1 for i in range(0, len(digits))[::-1]: digits[i] += carry if digits[i] > 9: digits[i] -= 10 carry = 1 else: carry = 0 if carry > 0: digits.insert(0, 1) return digits
0 0
- leetcode66题 题解 翻译 C语言版 Python版
- leetcode292题 题解 翻译 C语言版 Python版
- leetcode258题 题解 翻译 C语言版 Python版
- leetcode104题 题解 翻译 C语言版 Python版
- leetcode237题 题解 翻译 C语言版 Python版
- leetcode226题 题解 翻译 C语言版 Python版
- leetcode283题 题解 翻译 C语言版 Python版
- leetcode100题 题解 翻译 C语言版 Python版
- leetcode242题 题解 翻译 C语言版 Python版
- leetcode171题 题解 翻译 C语言版 Python版
- leetcode235题 题解 翻译 C语言版 Python版
- leetcode206题 题解 翻译 C语言版 Python版
- leetcode328题 题解 翻译 C语言版 Python版
- leetcode191题 题解 翻译 C语言版 Python版
- leetcode70题 题解 翻译 C语言版 Python版
- leetcode83题 题解 翻译 C语言版 Python版
- leetcode263题 题解 翻译 C语言版 Python版
- leetcode326题 题解 翻译 C语言版 Python版
- iOS每日一记——————————————之 自定义textfield的ClearButton
- PHP7 centos 源码安装
- java中hashcode()和equals()的详解
- Android Studio 导入篇(1)编译不通过
- Android动态改变Background后Padding无效的问题
- leetcode66题 题解 翻译 C语言版 Python版
- 一台电脑配置两个Mysql (5.6/5.7)免安装版配置
- Fedora 8.0下安装Perl过程
- 简单的使用MediaPlayer
- 不正确的使用HashMap引发死循环及元素丢失
- 【 视频 】crf与bitrate对照表
- 解决mySql中文乱码以及Eclipse插入中文出现乱码
- hashMap详解与实例
- cvvimage用copyof()显示图片到控件的错误