415. Add Strings
class Solution { public String addStrings(String num1, String num2) { int i = num1.length() - 1; int j = num2.length() - 1; StringBuilder sb = new StringBuilder(); int carry = 0; while (i >= 0 || j >= 0){ int sum = 0; if(i >= 0){ sum += num1.charAt(i) - '0'; i--; } if(j >= 0){ sum += num2.charAt(j) - '0'; j--; } sum += carry; sb.append(sum % 10); carry = sum / 10; } if( carry != 0){ sb.append(carry); } return sb.reverse().toString(); } }
This one is very similar to add binary , pretty much the same
The only difference is % 10, /10
When the two strings are exhausted, need to check if the carry is non zero, in the case 87 + 87 = 174
The carry is 1.
I think this is same as add binary , the carry can only be I or 0.
Reverse stringbuilder and change it to string
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both
num1andnum2is < 5100. - Both
num1andnum2contains only digits0-9. - Both
num1andnum2does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
posted on 2018-07-18 09:45 猪猪🐷 阅读(109) 评论(0) 收藏 举报
浙公网安备 33010602011771号