首页 > 代码库 > 49. 搜狗面试题: 大数相乘算法
49. 搜狗面试题: 大数相乘算法
分析:
大数能大到整形类型存储不了。须要借助于其它的算法,来完毕乘法运算。
能够使用口算乘法的步骤来模拟乘法操作。例如以下:
123
* 122
=
3 4 6
+ 3 4 6
+ 1 2 3
= 1 5 0 0 6
实现例如以下:
#include<iostream> #include<string.h> using namespace std; char* MutiBigerNum(char* a, char* b) { int len1 = strlen(a); int len2 = strlen(b); char* res = new char[len1 + len2 + 1]; memset(res, ‘0‘, len1+len2); for(int i=len1-1; i >= 0; i-- ) { int carry = 0; for(int j = len2 -1; j >= 0; j--) { int temp = (res[i + j+ 1] - ‘0‘) + carry + (a[i] - ‘0‘)*(b[j] - ‘0‘); carry = 0; if(temp >= 10) { carry = temp/10; } res[i+j+1] = temp%10 + ‘0‘; } res[i] = carry + ‘0‘; } return res; } int main(int argn, char** argv) { char *a = "122"; char *b = "123"; if(argn > 2) { a = argv[1]; b = argv[2]; } char* resnum = MutiBigerNum(a, b); if(strlen(resnum) > 0 && resnum[0] == ‘0‘) cout << a << "*" << b << "=" << resnum + 1 << endl; else cout << a << "*" << b << "=" << resnum << endl; return 0; }
执行结果例如以下:
./test
122*123=15006
./test 999 888
999*888=887112
49. 搜狗面试题: 大数相乘算法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。