UVa 10106 - Product

来源:互联网 发布:java红黑树删除 编辑:程序博客网 时间:2024/05/29 15:43


The Problem

The problem is to multiply two integers X, Y. (0<=X,Y<10250)

The Input

The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.

The Output

For each input pair of lines the output line should consist one integer the product.

Sample Input

12122222222222222222222222222

Sample Output

144444444444444444444444444

题意:
大数乘法。
分析:
模拟大数乘法,用一个数的每一位上的数去乘另一个数,然后累加求得最终结果。
代码:

#include <cstdio>#include <cstring>#include <iostream>#include <string>#define for1( i , a , b ) for( int i = a ; i <= b ; i++ )#define for2( i , a , b ) for( int i = a ; i >= b ; i-- )using namespace std ;int main(){char Ca[ 260 ] , Cb[ 260 ] ;int Ia[ 260 ] , Ib[ 260 ] , It[ 260 ] , Is[ 550 ] ;while( ~scanf( "%s%s" , Ca , Cb ) ) {if( Ca[ 0 ] == '0' || Cb[ 0 ] == '0' ) {cout << "0\n" ;continue ;} for1( i , 0 , 260 - 1 ) Ia[ i ] = Ib[ i ] = 0 ;memset( Is , 0 , sizeof( Is ) ) ;int lena = strlen( Ca ) , lenb = strlen( Cb ) ;int k = 0 ;for2( i , lena - 1 , 0 ) Ia[ k++ ] = Ca[ i ] - '0' ;//转换到 int 数组 k = 0 ;for2( i , lenb - 1 , 0 ) Ib[ k++ ] = Cb[ i ] - '0' ;int ws = 0 ;//ws 记录加到最终结果时从哪一位开始加  for1( i , 0 , lena - 1 ) {//Ia 的每一位乘以 Ib  int jin = 0 , j ;memset( It , 0 , sizeof( It ) ) ;//It 保存当前乘积值   for( j = 0 ; j <= lenb - 1 || jin ; j++ ) {It[ j ] = Ia[ i ] * Ib[ j ] + jin ;jin = It[ j ] / 10 ;It[ j ] %= 10 ;}jin = 0 ;for( k = 0 ; k <= j - 1 || jin ; k++ ) {//将当前乘积值加到最终结果 Is[ ws + k ] += It[ k ] + jin ;jin = Is[ ws + k ] / 10 ;Is[ ws + k ] %= 10 ;}ws++ ;}    for2( i , ws + k - 2 , 0 ) //输出结果      cout << Is[ i ] ;cout << endl ;}return 0 ;}



0 0
原创粉丝点击