Given two non-negative integers num1 and num2represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

需要考虑乘积的长度,以及乘积的每一位对应的是乘数中哪两个数字的乘积。

注意字符串首位出现0的情况,通常情况下至多首位为0,除了一个特殊情况乘数中有0,这样会造成String中多位为0,所以在开头要排除这个可能。

注意JAVA比较字符串相等必须用equals而不能用==;字符转换成int,除了-'0',还需要强制转换(char);char转成String,也要显示转换,使用String.valueOf

class Solution {
public String multiply(String num1, String num2) {
if(num1.equals("0")|| num2.equals("0")) return "0"; int[] product = new int[num1.length()+num2.length()]; //array to save the product
int m1;
int m2;
int p; for(int i = product.length-1; i >= 0; i--){ //iterate each bit of the product
for(int j = num2.length()-1; j>=0; j--){ //iterate each bit of multiplier2
if(i-j-1 < 0) continue;
if(i-j-1 >= num1.length()) break;
m2 = num2.charAt(j)-'0';
m1 = num1.charAt(i-j-1)-'0';
p = m1*m2;
product[i] += p;
}
} //calculate carry
for(int i = product.length-1; i > 0; i--){
if(product[i]<10) continue; product[i-1] += (product[i]/10);
product[i] %= 10;
} //transfrom integer to string
String result;
if(product[0] != 0) {
result = String.valueOf((char) (product[0] + '0'));
}
else result = "";
for(int i = 1; i < product.length; i++){
result += String.valueOf((char) (product[i] + '0'));
} return result;
}
}

最新文章

  1. C# 5.0新推出的async和await
  2. supersr--时间显示逻辑--&gt;NSDate+NSCalendar
  3. 字符串和整形数组的相互转化(JAVA程序)
  4. 使用dropwizard(5)--加入swagger
  5. php运行C++程序
  6. Chrome浏览器调试Android的Webview
  7. openresty + lua-resty-weedfs + weedfs + graphicsmagick动态生成缩略图(类似淘宝方案)
  8. SimpleDateFormat日期格式化总结
  9. mybatis源码解析之Configuration加载(二)
  10. sprindmvc
  11. Charles 抓包手机app
  12. JavaScript -- 时光流逝(三):js中的 String 对象的方法
  13. maven依赖包下载地址
  14. JVM 内部原理(四)— 基本概念之 JVM 结构
  15. android 8.0 intent安装apk失败屏幕闪过
  16. Spring Cloud Config 配置中心
  17. 转载 Python导入模块的几种姿势
  18. 基于aop的redis自动缓存实现
  19. 安装Cloudera Manager集群时首次运行命令部署客户端设置失败的解决办法(图文详解)
  20. Codeforces Round #395 (Div. 2) D. Timofey and rectangles

热门文章

  1. 【python学习之五】自定义函数实现用 Python 发送电子邮件
  2. Python与CSV文件(CSV模块)
  3. 【转】毛虫算法&mdash;&mdash;尺取法
  4. Sql 中的as是什么意思 + 无列名注入解析
  5. python之random随机函数
  6. 利用IKVM在C#中调Java程序(总结+案例)
  7. 第三周课程总结&amp;实验报告(一)
  8. Oracle JET 使用RequireJS第三方工具或库引入
  9. NDK下编译JNI
  10. ES6数值的拓展