码迷,mamicode.com
首页 > 编程语言 > 详细

66. Plus One Java solutions

时间:2016-05-03 16:01:40      阅读:162      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!