656

来源:互联网 发布:mac终端获取文件路径 编辑:程序博客网 时间:2024/06/07 01:30

2017.9.12

字符串的数学运算掌握的还可以。

就是有一点忽略了。

余数 tmp = (a + b + flag)%10;

进位 flag =(a + b + flag)/ 10;

这里进位和余数的计算顺序不能反了,不然flag 更新之后再计算tmp就会出现错误。

public class Solution {    /*     * @param num1: a non-negative integers     * @param num2: a non-negative integers     * @return: return product of num1 and num2     */public static String add(String num1,String num2){int l1 = num1.length() - 1;int l2 = num2.length() - 1;int flag = 0;String res = "";while(l1 >= 0 && l2 >= 0){int tmp = (num1.charAt(l1)-'0' + num2.charAt(l2)-'0' + flag)%10;flag = (num1.charAt(l1)-'0' + num2.charAt(l2)-'0' + flag)/10;res = Integer.toString(tmp) + res;l1--;l2--;}while(l1 >= 0){int tmp = (num1.charAt(l1)-'0' + flag)%10;flag = (num1.charAt(l1)-'0' + flag)/10;res =Integer.toString(tmp) + res;l1--;}while(l2 >= 0){int tmp = (num2.charAt(l2)-'0' + flag)%10;flag = (num2.charAt(l2)-'0' + flag)/10;res = Integer.toString(tmp) + res;l2--;}if(flag == 1){res = "1" + res;}return res;}public static String multiply(String num1, String num2) {        // write your code hereint l1 = num1.length();int l2 = num2.length();// 保证num2始终是位数较少的那一个。if(l1 < l2){String tmp = num1;num1 = num2;num2 = tmp;}String res = "0";for(int i = 0; i < num2.length() - 1; i++){for(int j = 0; j < num2.charAt(i) - '0'; j++){res = add(res,num1);}res = res + "0";}for(int j = 0; j < num2.charAt(num2.length() - 1) - '0'; j++){res = add(res,num1);}return res;    }}