码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Variant-Plus N

时间:2014-11-29 07:05:00      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

Given a non-negative number represented as an array of digits, plus N to the number.

The digits are stored such that the most significant digit is at the head of the list.

N is guaranteed to be non-negative.

Solution:

 1 public class Solution {
 2     public int[] plusN(int[] digits, int n) {
 3         int carry = n;
 4         int index = digits.length-1;
 5         while (carry>0 && 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>0){
14             String cStr = Integer.toString(carry);
15             res = new int[cStr.length()+digits.length];
16             for (int i=0;i<cStr.length();i++)
17                 res[i]=cStr.charAt(i)-‘0‘;
18             for (int i=0;i<digits.length;i++)
19                 res[i+cStr.length()]=digits[i];           
20         } else res = digits;
21         return res;
22     }
23 }

 

Leetcode Variant-Plus N

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/lishiblog/p/4129895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!