首页 > 编程语言 > 详细

66. Plus One Java solutions

时间:2016-05-03 16:00:49      阅读:279      评论: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.

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 }

 

66. Plus One Java solutions

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

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