43. Multiply Strings (JAVA)
2024-09-05 20:28:39
Given two non-negative integers num1
and num2
represented 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:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - 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;
}
}
最新文章
- C# 5.0新推出的async和await
- supersr--时间显示逻辑-->;NSDate+NSCalendar
- 字符串和整形数组的相互转化(JAVA程序)
- 使用dropwizard(5)--加入swagger
- php运行C++程序
- Chrome浏览器调试Android的Webview
- openresty + lua-resty-weedfs + weedfs + graphicsmagick动态生成缩略图(类似淘宝方案)
- SimpleDateFormat日期格式化总结
- mybatis源码解析之Configuration加载(二)
- sprindmvc
- Charles 抓包手机app
- JavaScript -- 时光流逝(三):js中的 String 对象的方法
- maven依赖包下载地址
- JVM 内部原理(四)— 基本概念之 JVM 结构
- android 8.0 intent安装apk失败屏幕闪过
- Spring Cloud Config 配置中心
- 转载 Python导入模块的几种姿势
- 基于aop的redis自动缓存实现
- 安装Cloudera Manager集群时首次运行命令部署客户端设置失败的解决办法(图文详解)
- Codeforces Round #395 (Div. 2) D. Timofey and rectangles