415. Add Strings
Posted wentiliangkaihua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了415. Add Strings相关的知识,希望对你有一定的参考价值。
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution { public String addStrings(String num1, String num2) { int l1 = num1.length(); int l2 = num2.length(); int carry = 0; int c1 = l1-1, c2 = l2-1; StringBuilder res = new StringBuilder(); while(c1 >= 0 || c2 >= 0){ int cur1 = c1 >= 0 ? (num1.charAt(c1) - ‘0‘) : 0; int cur2 = c2 >= 0 ? (num2.charAt(c2) - ‘0‘) : 0; int sum = cur1 + cur2 + carry; int digit = sum % 10; carry = sum / 10; res.insert(0, digit); if(c1 >= 0) c1--; if(c2 >= 0) c2--; } if(carry == 1){ res.insert(0, 1); System.out.println(carry); } return res.toString(); } }
和add two numbers差不多
以上是关于415. Add Strings的主要内容,如果未能解决你的问题,请参考以下文章