Java [Leetcode 43]Multiply Strings
2024-10-10 11:00:52
题目描述:
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
解题思路:
设置数组记录单个位置相乘的结果,最后负责相加进位。
代码如下:
public class Solution {
public String multiply(String num1, String num2) {
int num1Length = num1.length();
int num2Length = num2.length();
int d1, d2;
int carry = 0;
int temp;
int[] caculate = new int[num1Length + num2Length];
StringBuilder sb = new StringBuilder(); for (int i = num1.length() - 1; i >= 0; i--) {
d1 = num1.charAt(i) - '0';
for (int j = num2.length() - 1; j >= 0; j--) {
d2 = num2.charAt(j) - '0';
caculate[i + j + 1] += d1 * d2;
}
} for (int i = caculate.length - 1; i >= 0; i--) {
temp = (caculate[i] + carry) % 10;
carry = (caculate[i] + carry) / 10;
caculate[i] = temp;
} for (int num : caculate)
sb.append(num); while (sb.length() > 1 && sb.charAt(0) == '0') {
sb.deleteCharAt(0);
} return sb.toString(); }
}
最新文章
- apache httpd服务器403 forbidden的问题
- About_类与对象03
- CSS入门
- React组件性能优化
- ThreadLocal类学习笔记
- Apache Spark源码走读之8 -- Spark on Yarn
- iOS教程
- .net,mvc使用bootstrap做一个标准后台
- Java数组的内存管理
- windows store app Lifecycle
- quartz 的学习和使用。
- iOS10 CAAnimationDelegate的适配
- mysql的复杂查询,连接数据库
- Linux Server release 7.3 更换阿里网络yum源
- python网络-多进程(21)
- 图数据库项目DGraph的前世今生
- 【PHP篇】运算及流程控制
- jsp页面无法使用EL
- 20165313 《Java程序设计》第五周学习总结
- 关于配置 TeamCity 清理历史 artifacts 问题