大整数乘法
2015-10-11 22:20
330 查看
大整数 乘法运算: 乘法:其实乘法很简单,对于加法 进位放在下一位。但是对于乘法,如果数学功底扎实,就可以用连乘式推出以下结论: n位数乘m位数 那么最多有(n+m)位。 于是将数据存至数组中,那么就有 c[i+j]+=a[i]*b[j] if(c[i+j]>=10)//当然对于结果数组长度申请最好为 len_a+len_b+1 { c[i+j+1]+=c[i+j]/10; c[i+j]%=10; } <p>理论讲不太清楚,也不知道如何图解,大家直接看代码吧!代码可能较长,耐心看很容易看懂!</p><p>时间复杂度:O(n^2) 空间复杂度O(n)</p>
//大数乘法 简化运算 #include<iostream> #include<string> #include<cassert> using namespace std; int* TransStrToNumber(string& Ref);//字符串转换为数组 bool IsPostive(string& Ref1, string& Ref2);//判断结果是否为正数 int* SupMultip(string& Ref, string& Ref2);//大数相乘 void Print(int* pResult,int len,bool IsPostive);//输出函数 int* TransStrToNumber(string& Ref) { assert("" != Ref); if ('+' != Ref[0] && '-' != Ref[0]) { //Ref.insert(1, "+");//将用户输入的字符串 插入一个符号 //第一个参数是插在该位置之前 第二个参数必须为常量字符串 //这种方法无法插入在第一个位置 Ref = "+" + Ref; } int len = Ref.length()-1;//字符串长度比数组多1 int *pNumber = new int[len](); if (NULL == pNumber) { exit(0); } for (int j=len;j>=1; --j) { pNumber[len-j] = Ref[j] - 48;// 输入习惯是高位在前 而低位在后 但是为了简化计算 低位应该凡在前面 } return pNumber; } bool IsPostive(string& Ref1, string& Ref2) { int MinusCount = 0; bool IsPostive = true; if ( '-' == Ref1[0]) { ++MinusCount; } if ( '-' == Ref2[0]) { ++MinusCount; } if (1 == MinusCount % 2) { IsPostive = false; } return IsPostive; } int* SupMultip(string& Ref1, string& Ref2) { int* pNumber1 = TransStrToNumber(Ref1); int* pNumber2 = TransStrToNumber(Ref2); int len1 = Ref1.length()-1;//字符串多了一个符号位 int len2 = Ref2.length()-1; int* pResult = new int[len1+len2+1](); memset(pResult, 0, sizeof(int)*(len1 + len2+1)); if (NULL == pResult) { //exit(0);//可能内存申请失败 return NULL; } for (int i = 0; i < len1; ++i) { for (int j = 0; j < len2; ++j) { pResult[i + j] += pNumber1[i] * pNumber2[j];//一定注意是+= } } for (int i = 0; i < len1 + len2; ++i) { pResult[i + 1] += pResult[i] / 10; pResult[i] = pResult[i] % 10; } delete[] pNumber1; delete[] pNumber2; bool IsPostiveNumber = IsPostive(Ref1,Ref2); Print(pResult, len1 + len2+1,IsPostiveNumber); return pResult; } void Print(int* pResult,int len, bool IsPostive) { if (NULL == pResult) { exit(0); } int i = len-1; while (i>=0&&0 == pResult[i]) { --i;//循环跳出时 就是第一个不为0的数字 } if (-1 == i) { cout << "0" << endl; return; } if (IsPostive) { cout << "+"; } else { cout << "-"; } for (i; i >= 0; --i) { cout << pResult[i] << " "; } cout << endl; //delete[] pResult; } int main(void) { string str1 = "111111111111111"; string str2 = "-10000"; cin >> str1>>str2; int*pRef=SupMultip(str1, str2); if (pRef != NULL) { delete[] pRef; } return 0; }
相关文章推荐
- Spring注入单例模式问题2
- gns3 1.4.0b3 使用笔记,一些报错的处理
- swift单例和oc单例
- iOS 远程推送
- Foundation
- Linux折腾记录(2)
- Spring注解@Component、@Repository、@Service、@Controller区别
- java入门第二天作业预习运算符
- 夏洛特烦恼 的感想
- [路由交换]OSPF网络类型、DR/BDR、邻居,邻接关系
- 关于”running yum-complete-transaction first” 的提示信息
- 采用maven 对tomcat 进行自动部署
- setAttribute and getAttribute的用法 以及阻止<a>的href的默认属性
- Git 速查手册
- 网站搜索框添加语音搜索功能
- 沟通管理计划包括哪些内容?
- 2015下半年软考系统集成管理工程师10月8日作业
- 在项目中使用volley
- 第四周项目1 建立单链表
- 【WinForm窗体控件开发】之三续 窗体控件设计时的事件属性