标签:add dir build return represent code div == you
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
num1
and num2
is < 5100.num1
and num2
contains only digits 0-9
.num1
and num2
does not contain any leading zero.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差不多
标签:add dir build return represent code div == you
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13053767.html