你的位置:首页 > 软件开发 > Java > 66 Plus One

66 Plus One

发布时间:2015-04-12 00:01:44
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.

题目的意思是这样的 给出一个非负的数,用数组来表示这个数,比如说9999就是[9,9,9,9]当对这个数加一的时候,将这个数用数组的形式返回。

很容易想到一个简单的方法,设置一个进位,首先判断数组最后一个元素加上1后是否产生进位(等于10),如果产生进位就将该元素置为0,其他的元素也是同样的操作,在这边有个小技巧,题目中说的是对这个数+1那么可以认为起始的进位就是1。当其中一个元素小于10的时候就直接将数组返回;当最高位执行完后没有返回也就是说最高位产生了进位,那就要产生一个新的数组,最高位为1,其余都是0

 1 public class Solution { 2   public int[] plusOne(int[] digits) { 3     int n = digits.length; 4     int jinwei = 1; 5     int i; 6     for (i = n - 1; i >= 0; i--) { 7       digits[i] += jinwei; 8       if (digits[i] < 10) 9         return digits;10       /* 有进位 */11       else12         digits[i] = 0;13     }14     /* 表示最高位有进位 */15     int[] newdigits = new int[n + 1];16     newdigits[0] = 1;17     for (int k = 1; k < n + 1; k++)18       newdigits[k] = 0;19     return newdigits;20   }21 }

原标题:66 Plus One

关键词:

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

可能感兴趣文章

我的浏览记录