两个任意长度的长整数相乘(华为oj,C++)
来源:互联网 发布:淘宝onlyanna真名晓颖 编辑:程序博客网 时间:2024/05/17 23:34
<pre name="code" class="cpp">#include "oj.h"#include<iostream>int main(void){string strMultiplierA = "9999";string strMultiplierB = "9999";string strRst = "\0";multiply (strMultiplierA,strMultiplierB,strRst);cout << strRst;return 0;}/*****************************************************************************Prototype : multiplyDescription : 两个任意长度的长整数相乘, 输出结果Input pAram : const std::string strMultiplierA 乘数Aconst std::string strMultiplierB 乘数BOutput : std::string strRst 乘法结果Return Value : int 0 正确 -1 异常*****************************************************************************/int multiply (const std::string strMultiplierA,const std::string strMultiplierB, std::string &strRst) {/* 在这里实现功能 */string chengshuA = strMultiplierA;string chengshuB = strMultiplierB;int a = chengshuA.length();int b = chengshuB.length();int strRst_length = 0;int c = (a+1)*(b+1);int *p = new int[c];//逆序存放的结果int *pA = new int[a];//逆序存放的乘数Aint *pB = new int[b];//逆序存放的乘数B//测试是否有乘数为空if ((a == 0) || (b == 0))return -1;for (int i = 0; i != c; i++)p[i] = 0;//把乘数逆序放到数组pA中,若chengshuA是12345,则pA是54321for (string::size_type index = 0; index != chengshuA.length(); index++) pA[a-1-index] = chengshuA.at(index) - '0';//pA[(a-1) - index]for (string::size_type index = 0; index != chengshuB.length(); index++)pB[b-1-index] = chengshuB.at(index) - '0';for (int temp_b = 0; temp_b != b; temp_b++) //每个位循环相乘{for (int temp_a = 0; temp_a != a; temp_a++)//pA的每个位循环与pB[temp_b]相乘{//p[temp_a+temp_b]利用temp_b起到移位的作用,如temp_b是十位数,则在乘法计算中要向后移动移位。int temp = p[temp_a+temp_b] + pA[temp_a]*pB[temp_b];p[temp_a+temp_b] = temp % 10;int carry = temp/10; //进位int x = temp_a + temp_b +1;//c = (a+1)*(b+1),足够大;大数相加与数相乘同时计算,进位有可能是多位数while(carry != 0)//进位不等于0{p[x] = p[x] + carry%10;//若前面有进位,则提前把进位加到求和结果p[x]上carry = carry/10;x++;}}}while (c-- > 0) //判断结果有几位{if (p[c] != 0){strRst_length = c + 1;break;}}char ch;for (int i = strRst_length - 1; i >= 0 ; i--) //把结果放入字符串中{ch = p[i] + '0';strRst.push_back(ch);}if (strRst.empty())//如果结果为0,则输出字符串为“0”{strRst = "0";}return 0;}
0 0
- 两个任意长度的长整数相乘(华为oj,C++)
- 两个任意长度的长整数相乘(C语言、双向链表方法)
- 两个长整数相乘
- 任意长度的两个正整数相乘
- 关于两个长整数相乘的实现
- 两个任意长度整数的加减乘除
- c 两个整数相乘
- 任意长度的两个字符串数列相乘的算法实现
- 英雄会-----任意长度的两个正整数相乘
- Java任意两个大整数相乘
- 单链表实现两个长整数相乘
- 实现长整数的相乘
- 用汇编实现任意长度的两个整数相加
- 关于两个任意长度的数字相乘的代码设计(不使用BigDecimal的情况下)
- 两个整数的大数相乘
- 任意长度的两大数相乘
- 任意长整数加法运算(C++)实验文档
- 任意长度的整数加法C语言代码
- mongodb与mysql相比的优缺点
- Flower garden
- Leetcode205 同构字符串
- JAVA简单的爬虫代码
- 写在农历丙申年的开端
- 两个任意长度的长整数相乘(华为oj,C++)
- 第一个Servlet
- 【EASY ANDROID】转移到gitbook
- C语言中输入值时要注意一些内容
- Swift2.2 学习笔记(三) ___函数和闭包
- 创建模态对话框和非模态对话框的方法
- hadoop命令详解
- 滑动窗口联系
- 动态加载js文件的jsLoader代码