Java
public class Solution {
public String addStrings(String num1, String num2) {
int tmp=0;
int k=0;
int length1=num1.length();
int length2=num2.length();
int min=length1>length2? length2:length1;
int max=length1>length2? length1:length2;
String use;
if(length1>length2)
use=num1;
else
use=num2;
String string="";
int i;
for(i=0;i<max;)
{
int bitAdd;
if(i<min)
bitAdd=((int)num1.charAt(length1-1-i)-(int)('0')+(int)num2.charAt(length2-1-i)-(int)('0')+tmp);
else
bitAdd=((int)use.charAt(max-1-i)-(int)('0')+tmp);
k=bitAdd%10;
tmp=bitAdd/10;
System.out.println(bitAdd);
string=k+""+string;
i++;
}
if(tmp!=0) string=tmp+""+string;
return string;
}
}
Javascript
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function(num1, num2) {
var tmp=0;
var k=0;
var length1=num1.length;
var length2=num2.length;
var min=length1>length2? length2:length1;
var max=length1>length2? length1:length2;
var use;
if(length1>length2)
use=num1;
else
use=num2;
var string="";
var i;
for(i=0;i<max;)
{
var bitAdd;
if(i<min)
bitAdd=(parseInt(num1[length1-1-i])+parseInt(num2[length2-1-i])+tmp);
else
bitAdd=(parseInt(use[max-1-i])+tmp);
k=bitAdd%10;
tmp=(bitAdd-k)/10;
string=k+string;
i++;
}
if(tmp!==0) string=tmp+string;
return string;
};
注意Javascript做除法不会取整
优解,思路差不多,但是他这个写法很简练
public class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int carry = 0;
for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){
int x = i < 0 ? 0 : num1.charAt(i) - '0';
int y = j < 0 ? 0 : num2.charAt(j) - '0';
sb.append((x + y + carry) % 10);
carry = (x + y + carry) / 10;
}
return sb.reverse().toString();
}
}
网友评论