首页 > 其他 > 详细

Leetcode-Plus One

时间:2014-11-29 07:03:18      阅读:195      评论:0      收藏:0      [点我收藏+]

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.

Solution:

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         int carry = 1;
 4         int index = digits.length-1;
 5         while (carry==1 && index>=0){
 6             int val = digits[index]+carry;
 7             carry = val/10;
 8             val = val%10;
 9             digits[index]=val;
10             index--;
11         }
12         int[] res;
13         if (index<0 && carry==1){
14            res = new int[digits.length+1];
15            res[0]=carry;
16            for (int i=0;i<digits.length;i++)
17                res[i+1] = digits[i];
18         } else res = digits;
19         return res;
20     }
21 }

 

Leetcode-Plus One

原文:http://www.cnblogs.com/lishiblog/p/4129893.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!