您的位置:首页 > 其它

UVa 10106 - Product

2015-01-06 19:46 399 查看



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

12
12
2
222222222222222222222222


Sample Output

144
444444444444444444444444


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

#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 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: