PAT A1065 A+B and C (64bit)
试验大整数运算?我真不是故意的,只因为上了贼船,便想一条路走到黑。。。 对string不知抱有何种执念,直到搞到需要比较大小的时候软了,觉得还不如用long long直接比,然而换成long long之后又并没有直接比,大概是因为异号的时候要用减法,仍然需要知道绝对值大的那个,作为第一个参数,并让娃跟他一个姓 不过后来看到网上有同学全程用的string 绝对值开始用abs来着,试了C++ 11下可以接受long long,but我的电脑上不行,又不敢直接加负号,怕取到下限时溢出。。。只好写了个cmp统一解决比较大小和绝对值的问题,,, 负数转BigInt的时候会把每一位都给搞成负的(a % b,a < 0时,不管b的正负,结果都是负的),又打了补丁,浪费感情,还不如用string。。。 大整数加减法别忘了出了循环之后还有一件事情要做(进位和前面的0) 最最可恶的是,这一番作死的操作之后,居然最后一个测试点挂了。。。不知道是为毛
#include <iostream>
using namespace std;
struct BigInt{
int len = 0 ;
int data[ 100 ] = { 0 } ;
int sign = 1 ;
} ;
BigInt convert ( long long ll) {
BigInt res;
if ( ll < 0 ) res. sign = - 1 ;
do {
res. data[ res. len ++ ] = ll % 10 ;
if ( res. sign == - 1 ) res. data[ res. len - 1 ] = - res. data[ res. len - 1 ] ;
ll / = 10 ;
} while ( ll) ;
return res;
}
BigInt add ( BigInt a, BigInt b) {
BigInt res;
int carry = 0 ;
for ( int i = 0 ; i < a. len || i < b. len; i ++ ) {
res. data[ res. len ++ ] = ( a. data[ i] + b. data[ i] + carry) % 10 ;
carry = ( a. data[ i] + b. data[ i] + carry) / 10 ;
}
if ( carry) res. data[ res. len ++ ] = 1 ;
return res;
}
BigInt _minus ( BigInt a, BigInt b) {
BigInt res;
for ( int i = 0 ; i < a. len || i < b. len; i ++ ) {
if ( a. data[ i] < b. data[ i] ) {
a. data[ i] + = 10 ;
a. data[ i + 1 ] -- ;
}
res. data[ res. len ++ ] = a. data[ i] - b. data[ i] ;
}
while ( res. data[ res. len - 1 ] == 0 && res. len > 1 ) {
res. len -- ;
}
return res;
}
int cmp ( BigInt a, BigInt b, bool abs) {
if ( ! abs && a. sign != b. sign) return a. sign - b. sign;
else {
if ( a. len != b. len) {
int diff = ( a. len - b. len) ;
if ( ! abs) diff * = a. sign;
return diff;
}
else {
for ( int i = a. len - 1 ; i >= 0 ; i -- ) {
if ( a. data[ i] != b. data[ i] ) {
int diff = ( a. data[ i] - b. data[ i] ) ;
if ( ! abs) diff * = a. sign;
return diff;
}
}
return 0 ;
}
}
}
#define DEBUG
int main ( ) {
#ifdef DEBUG
freopen ( "1.txt" , "r" , stdin ) ;
#endif
int num;
cin >> num;
for ( int i = 0 ; i < num; i ++ ) {
long long A, B, C;
cin >> A >> B >> C;
C = C << 62 ; cout << C << endl;
BigInt a = convert ( A) ;
BigInt b = convert ( B) ;
BigInt c;
if ( a. sign == b. sign) {
c = add ( a, b) ;
c. sign = a. sign;
} else {
if ( cmp ( a, b, true ) > 0 ) {
c = _minus ( a, b) ;
c. sign = a. sign;
}
else {
c = _minus ( b, a) ;
c. sign = b. sign;
}
}
printf ( "Case #%d: " , i + 1 ) ;
BigInt cc = convert ( C) ;
cout << "c = " << c. sign << ' ' ;
for ( int i = c. len - 1 ; i >= 0 ; i -- ) cout << c. data[ i] ;
if ( cmp ( c, cc, false ) > 0 ) printf ( "true\n" ) ;
else printf ( "false\n" ) ;
}
return 0 ;
}