66. Plus One Java solutions

时间:2016-05-03 16:00:49   收藏:0   阅读:279

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.

Subscribe to see which companies asked this question

题目大意就是用一个int数组来模拟十进制数加1的计算,需要注意的地方就是溢出的情况.

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         int len = digits.length;
 4         digits[len-1]++;
 5         boolean flag = false;//是否溢出
 6         for(int i=len -1; i>=0;i--){
 7             if(digits[i] >= 10) {
 8                 if(i != 0){
 9                     digits[i-1]++;
10                  }else{
11                      flag =true;
12                  }
13                 digits[i] -= 10;
14             }
15         }
16         if(flag == true){
17             int[] res = new int[len+1];
18             res[0] = 1;
19             for(int i = 0;i<len;i++){
20                 res[i+1] = digits[i];
21             }
22             return res;
23         }else{
24             return digits;
25         }
26         
27     }
28 }

 

原文:http://www.cnblogs.com/guoguolan/p/5455074.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!