字符串转为数字处理 效率更高(学习一下)
转为int数组再转为字符串
class Solution {
public String multiply(String num1, String num2) {
int m = num1.length();
int n = num2.length();
int[] pos = new int[m + n];
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j;
int p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = sum % 10;
}
}
StringBuilder sb = new StringBuilder();
// 消除前面是0的情况,有了值才append0
for (int p : pos) if (sb.length() != 0 || p != 0) sb.append(p);
return sb.length() == 0 ? "0" : sb.toString();
}
}
转为char数组 再转为字符串
class Solution {
public String multiply(String num1, String num2) {
if(num1.equals("0")||num2.equals("0"))
return "0";
int m=num1.length();
int n=num2.length();
char[] nums1 = num1.toCharArray();
char[] nums2 = num2.toCharArray();
int [] res = new int[m+n];
for(int i=m-1;i>=0;i--)
{
for(int j=n-1;j>=0;j--)
{
res[i+j+1] = res[i+j+1]+(nums1[i]-'0')*(nums2[j]-'0');
}
}
for(int i=m+n-1;i>=0;i--)
{
if(res[i]>9)
{
res[i-1]=res[i-1]+res[i]/10;
res[i]=res[i]%10;
}
}
StringBuffer sb = new StringBuffer();
for(int i=0;i<=m+n-1;i++)
{
sb.append(res[i]);
}
if(sb.charAt(0)=='0')
sb = sb.deleteCharAt(0);
return sb.toString();
}
}