leetcode:Multiply Strings(JAVA)

    xiaoxiao2024-11-30  8

    模拟手乘加法实现 代码:

    public String multiply(String num1, String num2) { int len1 = num1.length(), len2 = num2.length(); if (len1 <= 0 && len2 <= 0) return ""; String res = ""; String tempRes = ""; int temp = 0, jinwei = 0; for (int i = len1 - 1; i >= 0; i--) { if (num1.charAt(i) == '0') continue; for (int j = len2 - 1; j >= 0; j--) {// temp = (num1.charAt(i) - 48) * (num2.charAt(j) - 48) + jinwei; if (temp > 9) { jinwei = temp / 10; tempRes = temp % 10 + tempRes; } else { tempRes = temp + tempRes; jinwei = 0; } } if (jinwei != 0) tempRes = jinwei + tempRes; // 添加0 if (!tempRes.equals("0")) { for (int j = i + 1; j < len1; j++) { tempRes = tempRes + "0"; } res = addition(res, tempRes); } tempRes = ""; jinwei = 0; } if (res.isEmpty()) return "0"; return res; } // 加法 public String addition(String num1, String num2) { int len1 = num1.length(), len2 = num2.length(); if (len1 <= 0 && len2 <= 0) { return ""; } String res = ""; int maxLen = len1 > len2 ? len1 : len2; int temp = 0, jinwei = 0; int index2 = len2 - 1; for (int i = len1 - 1; i >= 0; i--) { if (index2 >= 0) { temp = num1.charAt(i) + num2.charAt(index2--) - 96 + jinwei; // 处理进位 if (temp > 9) { jinwei = 1; res = temp % 10 + res; } else { res = temp + res; jinwei = 0; } } else { temp = num1.charAt(i) - 48 + jinwei; if (temp > 9) { jinwei = 1; res = temp % 10 + res; } else { res = temp + res; jinwei = 0; } } } if (index2 >= 0) { for (int i = index2; i >= 0; i--) { temp = num2.charAt(i) - 48 + jinwei; if (temp > 9) { jinwei = 1; res = temp % 10 + res; } else { res = temp + res; jinwei = 0; } } } if (jinwei!=0) res = jinwei+res ; return res; }
    转载请注明原文地址: https://ju.6miu.com/read-1294117.html
    最新回复(0)