你的位置:首页 > 软件开发 > Java > [LeetCode] Plus One

[LeetCode] Plus One

发布时间:2015-08-14 14:00:08
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 d ...

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.

 

     据说这道题在google的面试中出现频率很高呀。虽然不知道为什么。~

     这道题还是很好思考的。

     比较麻烦的是如果到最开头还是需要继续进位的话就要新建一个长度是原来array长度+1的数组然后将第一个数设为1,后面和原array的一样。

     至于为啥就不说了。应该很好理解的。~

     另外记得要写break,不用进位后计算也就停止了。

     代码如下:

public class Solution {  public int[] plusOne(int[] digits) {    int length=digits.length;    for(int i=length-1;i>=0;i--){      if(digits[i]==9){        digits[i]=0;      }else{        digits[i]=digits[i]+1;        break;      }      if(i==0&&digits[i]==0){        int[] temp=new int[digits.length+1];        temp[0]=1;        for(int j=1;j<digits.length+1;j++){          temp[j]=digits[j-1];        }        digits=temp;              }    }    return digits;  }}

原标题:[LeetCode] Plus One

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录