首页 > 代码库 > Leetcode Variant-Plus N
Leetcode Variant-Plus N
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。