LeetCode 43. Multiply Strings(乘法)
2016-05-20 10:46
323 查看
原题网址:https://leetcode.com/problems/multiply-strings/
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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
方法:模拟乘法运算。
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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
方法:模拟乘法运算。
public class Solution { public String multiply(String num1, String num2) { int[] n1 = new int[num1.length()]; int[] n2 = new int[num2.length()]; int[] m = new int[num1.length() + num2.length()]; for(int i=0; i<n1.length; i++) { n1[n1.length-1-i] = num1.charAt(i)-'0'; } for(int i=0; i<n2.length; i++) { n2[n2.length-1-i] = num2.charAt(i)-'0'; } for(int i=0; i<n1.length; i++) { int carry = 0; for(int j=0; j<n2.length; j++) { int mul = m[i+j] + n1[i]*n2[j] + carry; m[i+j] = mul % 10; carry = mul / 10; } if (carry > 0) m[i+n2.length] += carry; } boolean notZero = false; StringBuilder sb = new StringBuilder(); for(int i=m.length-1; i>=0; i--) { if (m[i] > 0) notZero = true; if (notZero) sb.append(m[i]); } if (!notZero) sb.append(0); return sb.toString(); } }
相关文章推荐
- nginx 并发数
- 优秀程序员的十个习惯
- Java中Properties的使用详解
- [Tool] Python几个windows版本的区别
- AfinalHttp的AjaxBack简单封装
- Java 连接hbase 进行简单操作
- mac电脑使用
- 0.1 Spark Streaming 实现思路与模块概述
- 毛玻璃效果
- Linux如何在虚拟机中挂载iso yum源
- C++第六次实验—循环(实验)
- JSON的输出方式
- 从网络上收集的爬虫工具,推荐基于python的工具
- iOS开发-做项目中遇到的坑
- SQL学习笔记5——用代码实现对列的 增、删、改和约束
- thinkPHP3.x常量整理(预定义常量/路径常量/系统常量)
- 代码加约束VFL语法的详细使用介绍(代替Autolayout进行布局,比Autolayout更简单明了,生动直观)
- JMX
- iOS 左右两列按钮之间进行连线
- XSS攻击及防御