您的位置:首页 > 其它

LeetCode066 Plus One

2017-04-14 21:41 405 查看
详细见:leetcode.com/problems/plus-one

Java Solution:
github

package leetcode;

public class P066_PlusOne {
public static void main(String[] args) {
int[] ans = new Solution().plusOne(new int[] { 9, 9, 8 });
tools.Utils.printArray(ans, 10);
}
/*
* 0 ms
* 43.01%
*/
static class Solution {
public int[] plusOne(int[] digits) {
if (digits == null || digits.length == 0)
return new int[] {1};
digits[digits.length - 1] ++;
int carry = 0, index = digits.length - 1;
do {
if (index == -1) {
int[] temp = new int[digits.length + 1];
System.arraycopy(digits, 0, temp, 1, digits.length);
temp[0] = 1;
digits = temp;
break;
} else {
digits[index] += carry;
carry = digits[index] / 10;
digits[index] = digits[index] % 10;
index --;
}
} while (carry != 0);
return digits;
}
}
}


C Solution: github

/*
url: leetcode.com/problems/plus-one
AC
*/

#include <stdio.h>
#include <stdlib.h>

int* plusOne(int* d, int dn, int* rn) {
int c = 0, i = 0;
int* r = (int*) malloc(sizeof(int) * (dn + 1));

r[dn] = d[dn-1] + 1;
c = r[dn] / 10;
r[dn] = r[dn] % 10;
for (i = dn-1; i > 0; i --) {
r[i] = c + d[i-1];
c = r[i] / 10;
r[i] = r[i] % 10;
}
if (c == 0) {
*rn = dn;
return r + 1;
} else {
*rn = dn+1;
r[0] = c;
return r;
}
}

int main() {
int d[] = {9, 9, 8};
int rn = 0;
int* a = plusOne(d, 3, &rn);
int i = 0;
for (i = 0; i < rn; i ++)
printf("%d ", a[i]);
printf("\r\n");
}

Python Solution:
github

#coding=utf-8

'''
url: leetcode.com/problems/plus-one
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月14日
@details: Solution: 45ms 63.57%
'''

class Solution(object):
def plusOne(self, d):
"""
:type d: List[int]
:rtype: List[int]
"""
if d == None or len(d) == 0: return [1]
dn = len(d)
d[dn-1] += 1
c = 0
for i in range(dn-1, -1, -1):
d[i] += c
c = d[i] // 10
d[i] = d[i] % 10
if c != 0: d.insert(0, c)
return d
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode