`
xitonga
  • 浏览: 583884 次
文章分类
社区版块
存档分类
最新评论

Multiply Strings 两个字符串代表数字相乘@LeetCode

 
阅读更多

这道题一开始觉得很麻烦,后来参考了http://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/comment-page-1/#comment-122

才知道有如此优雅的写法,这样的写法一遍就可以写出bug free的代码。

思路:

1 翻转string

2 建立数组,双层循环遍历两个string,把单位的乘积累加到数组相应的位置

3 处理进位并输出

4 注意前导零的corner case


package Level4;

/**
 * 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.
 * 
 */
public class S43 {

	public static void main(String[] args) {
		String num1 = "0";
		String num2 = "0";
		System.out.println(multiply(num1, num2));
	}

	public static String multiply(String num1, String num2) {
		// 先把string翻转
		String n1 = new StringBuilder(num1).reverse().toString();
		String n2 = new StringBuilder(num2).reverse().toString();
		
		int[] d = new int[n1.length()+n2.length()];		// 构建数组存放乘积
		for(int i=0; i<n1.length(); i++){
			for(int j=0; j<n2.length(); j++){
				d[i+j] += (n1.charAt(i)-'0') * (n2.charAt(j)-'0');		// 在正确位置累加乘积
			}
		}
		
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<d.length; i++){
			int digit = d[i]%10;		// 当前位
			int carry = d[i]/10;		// 进位
			if(i+1<d.length){
				d[i+1] += carry;
			}
			sb.insert(0, digit);		// prepend
		}
		
		// 移除前导零
		while(sb.charAt(0)=='0' && sb.length()>1){
			sb.deleteCharAt(0);
		}
		return sb.toString();
	}

}


分享到:
评论

相关推荐

    leetcode字符串括号level-leetcode:LeetCode解题记录

    leetcode字符串括号level LeetCode LeetCode 解题记录 Go 使用 Go 语言的解题记录 longestCommonPrefix 最长公共前缀 checkInclusion 字符串的排列 multiply 字符串相乘 reverseWords 翻转字符串里的单词 ...

    字符串相乘1

    示例 1:输出: "6"示例 2:输出: "56088"string multiply(string num1, string num2) {//对存储空间 扩

    LeetCode最全代码

    # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License]...

    leetcode卡-LeetCode:LeetCode题解

    字符串问题 ID Title C++ 难度 备注 0008 String to Integer(atoi) :star: :star: :star: 注意细节,溢出 ---- strlen :star: :star: :star: const char,size_t类型 ---- strcpy :star: :star: :star: 字符串复制,...

    Hadoop mapreduce 实现MatrixMultiply矩阵相乘

    Hadoop mapreduce 实现MatrixMultiply矩阵相乘

    leetcodepython001-LeetCode:力码

    建立两个个主要资料夹(题目收集、学习内容)+一个玩整的README整理 题目 主要以Python记录于VScode上 先记录头150题 学习 以JupyterNotebook为主 纪录各种资料结构、演算法等 Progress Array 015 3Sum 016 3Sum ...

    Python 实现两个列表里元素对应相乘的方法

    方法一: 结合zip函数,使用map函数: List1 = [1,2,3,4] List2 = [5,6,7,8] List3 = map(lambda (a,b):a*b,zip(List1,...以上这篇Python 实现两个列表里元素对应相乘的方法就是小编分享给大家的全部内容了,希望能

    python入门(1).doc

     /usr/bin/python #运行这行程序会出错,提示你字符串和数字不能连接,于是只好用内置函数进行转换 a=2 b="test" c=str(a)+b d="1111" e=a+int(d) #How to print multiply values print ("c is %s

    python入门实例.docx

     /usr/bin/python #运行这行程序会出错,提示你字符串和数字不能连接,于是只好用内置函数进行转换 a=2 b="test" c=str(a)+b d="1111" e=a+int(d) #How to print multiply values print ("c is %s

    leetcode答案-LeetCodeExercise:算法

    可以定义两个变量pre(表示子串的前端)、i(表示字符串的当前位置)、maxLength(当前子串最长的长度) 3. 开始循环整个字符串,如果遇到了相同的字符,则计算当前子串长度,并且与maxLength做比较,并且pre的位置转移到(i...

    Leetcode扑克-leetcode:Leetcode算法实践

    Leetcode扑克 Leetcode Starting from 2020/08/02 Leetcode practice with Python (for now) Daily Challenge + Selected ...Leetcode ...字符串 循环遍历即可 algorithm-pattern: quick start 43 Multiply S

    C++大数相乘程序源代码

    大数乘法函数Multiply。... 输入:两个任意长度的10进制整数序列字符串,如4567891234567890或者101。输出:一个10进制整数序列字符串,为所输入两个数的乘积,如4567891234567890*101=461357014691356890 。

    leetcode和oj-LeetCodeCppUtilities:很少有丑陋但有用的C++代码片段用于Leetcode练习

    文件操作:一个简单的解析器,可以解析Leetcode中最常用的测试用例格式。 ["aaaaaaa",ccccccc"...] 常见的binary search模板。 二叉树: print 、 create 、 array based create 、 level print 。 去做: 更好地...

    对python中的乘法dot和对应分量相乘multiply详解

    今天小编就为大家分享一篇对python中的乘法dot和对应分量相乘multiply详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

    交叉相乘计算器「Cross Multiply Calculator」-crx插件

    计算交叉相乘的比例,比率,大小,… 这个非常简单的扩展使您可以使用交叉乘法规则/矢量叉积计算(也称为“三则规则”计算)来计算比例值。 可用于按比例调整图像,视频等的大小。 支持语言:English

    记单词-multiply的意思用法总结大全.docx

    记单词-multiply的意思用法总结大全.docx

    Floating-Point Fused Multiply-Add Architectures

    Floating-Point Fused Multiply-Add Architectures,关于浮点乘加融合部件设计的博士论文2007

    ten_simple_JS_exercises:练习练习以恢复

    定义一个函数 max() ,它接受两个数字作为参数并返回其中最大的一个。 使用 Javascript 中可用的 if-then-else 构造。 定义一个函数 maxOfThree(),它接受三个数字作为参数并返回其中最大的一个。 编写一个函数,...

    Ten-Simple-Javascript-Exercises:铁院。 有趣的小练习

    定义一个函数max() ,它接受两个数字作为参数并返回其中最大的一个。 使用 Javascript 中可用的 if-then-else 构造。 定义一个函数maxOfThree() ,它接受三个数字作为参数并返回其中最大的一个。 编写一个函数,...

    multiply-array:将数组中的所有项目相乘

    将数组中的所有项目相乘 安装 $ npm install --save multiply-array 用法 var multiplyArray = require ( 'multiply-array' ) ; multiplyArray ( [ 2 , 2 , 4 ] ) ; //=&gt; 16 执照 麻省理工学院:copyright:

Global site tag (gtag.js) - Google Analytics