Plus One

原创 2015年07月08日 00:03:22

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.

题意:一个整数按位存储于一个int数组中,排列顺序为:最高位在array[0] ,最低位在[n-1],例如:98,存储为:array[0]=9; array[1]=8;

解题思路,从数组的最后一位开始加1,需要考虑进位,如果到[0]位之后仍然有进位存在,需要新开一个长度为(n.length + 1)的数组,拷贝原来的数组。

代码如下:

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits==null||digits.length==0) return null;
        int carry = 1;
        int sum = 0;
        int len = digits.length;
        for(int i=len-1;i>=0;i--){
            sum = digits[i]+carry;
            digits[i] = sum%10;
            carry = sum/10;
        }
        if(carry>0){
            int[] a = new int[len+1];
            a[0] = carry;
            for(int i=0;i<len;i++){
                a[i+1] = digits[i];
            }
            return a;
        }
        return digits;
        
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode Plus One

题目: Given a non-negative number represented as an array of digits, plus one to the number. T...

LeetCode --- 66. Plus One

题目链接:Plus One Given a non-negative number represented as an array of digits, plus one to the number...

66. Plus One某数+1(通过放到数组里)--Array

66. Plus One某数+1(通过放到数组里)--Array Given a non-negative number represented as an array of digits, plu...

leetcode 66. Plus One

leetcode 66. Plus One 题目大意:给定一个非负整数,存储在数组中,把这个数字加1,这个数的最高位在最前面。 解题思路:如果这个数的最低位为小于9,直接加到最低位去 如果这个数的最低...

[LeetCode]Plus One 优化

题目 Given a non-negative number represented as an array of digits, plus one to the number. The digits...
  • hjh00
  • hjh00
  • 2015-11-03 11:48
  • 437

Leetcode: Plus One

题目: Given a non-negative number represented as an array of digits, plus one to the number.The digit...

leetcode笔记:Plus One

一道高精度计算的题,从低位到高位进行计算,同时考虑进位的问题,若最高位计算结果还有进位,就需要在最高位前面添加一位。可做到时间复杂度为O(n),空间复杂度为O(1)。

【LeetCode-面试算法经典-Java实现】【066-Plus One(加一)】

【066-Plus One(加一)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a non-negative number represented as a...

LeetCode:Plus One

题目描述: Given a number represented as an array of digits, plus one to the number. 题目解释: 输入的数组digits...

leetcode-66. Plus One

Given a non-negative number represented as an array of digits, plus one to the number. The digits...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)