leetcode-415. Add Strings
Posted 世人谓我恋长安,其实只恋长安某
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-415. Add Strings相关的知识,希望对你有一定的参考价值。
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.
java代码:
public class Solution { public String addStrings(String num1, String num2) { int len1=num1.length()-1; int len2=num2.length()-1; StringBuilder sb=new StringBuilder(); int sum=0,carry=0; while(len1>=0||len2>=0){ int a=len1>=0?num1.charAt(len1)-‘0‘:0; int b=len2>=0?num2.charAt(len2)-‘0‘:0; sum=a+b+carry; if(sum>9){ sb.insert(0,sum%10); carry=1; sum=0; }else{ sb.insert(0,sum); sum=0; carry=0; } len1--; len2--; } if(carry==1){ sb.insert(0,1); } return sb.toString(); } }
以上是关于leetcode-415. Add Strings的主要内容,如果未能解决你的问题,请参考以下文章