Multiply Strings
来源:互联网 发布:党员干部必知的新词 编辑:程序博客网 时间:2024/05/16 19:14
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.
说明:模拟手工计算两个整数的乘积,注意每轮乘积最高位的进位和乘积为0的情况。
代码:
char* multiply(char* num1, char* num2) { char *zero = "0"; if(strcmp(num1, zero) == 0 || strcmp(num2, zero) == 0) return zero; int len1 = strlen(num1), len2 = strlen(num2); //逆序存放乘积 char *ret = (char *)malloc(sizeof(char) * (len1+len2+1)); memset(ret, '0', sizeof(char) * (len1+len2+1)); int i = 0, j = 0; for(i = 0; i <= len1-1; i++) { //乘数为0则跳过这次循环,开始下一次循环 if(num1[len1-1-i] == '0') continue; int carry = 0; int n1 = num1[len1-1-i] - '0'; for(j = 0; j <= len2-1; j++) { int n2 = num2[len2-1-j] - '0'; int sum = n1 * n2 + ret[i+j] - '0' + carry; carry = sum / 10; ret[i+j] = sum % 10 + '0'; } if(carry) ret[i+len2] = carry + '0'; } ret[len1+len2] = '\0'; // printf("%s\n", ret); char *p = ret, *q = &ret[len1+len2-1]; char tmp; //将逆序的乘积转换成正序 while(p < q) { tmp = *p; *p = *q; *q = tmp; p++; q--; } //如100*100,再ret所指字符数组里原来存放"000010",翻转后变成"010000",需要去掉开头的'0' if(*ret == '0') return ret+1; else return ret;}
0 0
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- ListView 嵌套 EditText 显示错位
- HDU1335 POJ1546 UVA389 Basically Speaking
- Linux下利用NFS和Samba在source insight上快速开发应用程序
- 页面添加蒙版,但是不影响页面其他事件响应
- IOS开发广告接入iAD框架_InMobi框架
- Multiply Strings
- 利用IIS服务发布网站
- 我的wine中文字体配置笔记
- if else与三目运算符的区别
- iOS 获取网络图片的大小
- 二维数组排序 sort
- ACM--字母序列--HDOJ 1020--Encoding--字符串
- CF Round #361 (Div. 2) 689C. Mike and Chocolate Thieves
- Adb connection Error:远程主机强迫关闭了一个现有的连接