simple java solution


  • 0
    2
    public class Solution {
        public String multiply(String num1, String num2) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < num1.length() + num2.length(); i++) {
                sb.append('0');
            }
            for (int i = 0; i < num1.length(); i++) {
                for (int j = 0; j < num2.length(); j++) {
                    addProduct(sb, num1.charAt(i), num2.charAt(j), num1.length() + num2.length() - 2 - i - j);
                }
            }
            String ret = sb.toString();
            while (ret.length() > 1 && ret.charAt(0) == '0') {
                ret = ret.substring(1);
            }
            return ret;
        }
        private void addProduct(StringBuilder sb, char c1, char c2, int offset) {
            int i = (c1 - '0') * (c2 - '0');
            add(sb, i / 10, offset + 1);
            add(sb, i % 10, offset);
        }
        private void add(StringBuilder sb, int i, int offset) {
            if (i == 0) {
                return;
            }
            int sum = sb.charAt(sb.length() - 1 - offset) - '0' + i;
            sb.setCharAt(sb.length() - 1 - offset, (char)(sum % 10 + '0'));
            add(sb, sum / 10, offset + 1);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.