当前位置:网站首页>[high precision] decimal integer addition

[high precision] decimal integer addition

2022-06-11 19:38:00 MC happy bitter Xiao afraid

subject :

 Title Description 

 Calculation x Hexadecimal integer a+b Value ,( 0 <= a, b <= 10^100);
 Input format 

 first line : An integer x( 2 <=x<=10 || x=16), Represents the two integer digits of the second line x Hexadecimal number .

 The second line : Two separated by spaces x Hexadecimal integer a and b.
 Output format 

 a line :a+b Value  ( Output in original decimal )
 Input and output sample Columns 
 sample input 110

10 15

 sample output 125

 sample input 216

A B

 sample output 215

Ideas :
Change on the high-precision template :
What needs to be changed :
① When storing in reverse order, it needs to be converted to x Base number
② Calculation %10 and /10 Change to %x and /x
③ When saving the calculation results, you should convert them to x Base number

CODE:

#include <bits/stdc++.h>

using namespace std;

const int N = 10010 ;
int a[N] , b[N] , c[N] ;
string ans ;
string add(string as , string bs , int x)
{
    
	ans.clear () ;
	memset (a , 0 , sizeof (a)) ;
	memset (b , 0 , sizeof (b)) ;
	memset (c , 0 , sizeof (c)) ;
	int alen = as.size () , blen = bs.size () , clen = max (alen , blen) + 1 ;
	for (int i = 1; i <= alen; i++)
	{
    
		if (as[alen - i] >= '0' && as[alen - i] <= '9')
			a[i] = as[alen - i] - '0'  ;
		else 
			a[i] = as[alen - i] - 'A' + 10 ;
	}
	for (int i = 1; i <= blen; i++)
	{
    
		if (bs[blen - i] >= '0' && bs[blen - i] <= '9')
			b[i] = bs[blen - i] - '0' ;
		else 
			b[i] = bs[blen - i] - 'A' + 10 ;
	}
	for (int i = 1; i < clen; i++)
	{
    
		c[i] += a[i] + b[i] ;
		c[i + 1] = c[i] / x ;
		c[i] %= x ;
	}
	while (c[clen] == 0 && clen > 1) 
	{
    
		clen -- ;
	}
	for (int i = clen; i >= 1; i --)
	{
    
		if (c[i] >= 0 && c[i] <= 9)
			ans += c[i] + '0' ;
		else 
			ans += c[i] - 10 + 'A' ;
	}
	return ans ;
}

int main()
{
    


	string a , b ;
	int x ;
	cin >> x >> a >> b ;
	cout << add (a , b , x) ;


    return 0;
}

AC 了

原网站

版权声明
本文为[MC happy bitter Xiao afraid]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111927148608.html