#ifndef _BIGNUM_HPP_
#define _BIGNUM_HPP_
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class BigNum;
BigNum operator+(const BigNum& lhs, const BigNum& rhs);
ostream& operator<<(ostream& os, const BigNum& rhs);
void Add(const BigNum& lhs, const BigNum& rhs, BigNum& res);
class BigNum
{
public:
BigNum(int n) : value(n){}
BigNum(const string& s);
friend BigNum operator+(const BigNum& lhs, const BigNum& rhs);
friend ostream& operator<<(ostream& os, const BigNum& rhs);
friend void Add(const BigNum& lhs, const BigNum& rhs, BigNum& res);
private:
vector<char> value;
};
#endif
#include "BigNum.hpp"
BigNum::BigNum(const string& s):value(s.length())
{
int j = value.size();
for(string::const_iterator it = s.begin(); it != s.end(); it++)
{
j--;
value[j] = *it;
}
}
ostream& operator<<(ostream& os, const BigNum& rhs)
{
size_t i = rhs.value.size();
bool zero = false;
if( i == 1)
return os << rhs.value[0];
if(rhs.value[ i - 1 ] == '0')
zero = true;
while( i > 0 )
{
i--;
while(zero == true)
{
i--;
if(rhs.value[i] != '0')
zero = false;
}
os << rhs.value[i];
}
return os;
}
void Add(const BigNum& lhs, const BigNum& rhs, BigNum& res)
{
int carry = 0;
char c = 0;
char tmp = 0;
size_t i = 0;
for( ; i < rhs.value.size(); i++)
{
tmp = lhs.value[i] + rhs.value[i] + carry - '0';
if( tmp > '9' )
{
carry = 1;
tmp -= 10;
}
else
{
carry = 0;
}
res.value[i] = tmp;
}
while( carry != 0 && i < lhs.value.size() )
{
tmp = lhs.value[i] + carry;
if( tmp > '9' )
{
carry = 1;
tmp = '0';
}
else
{
carry = 0;
}
res.value[i] = tmp;
i++;
}
if( carry > 0)
res.value[i] = '1';
}
BigNum operator+(const BigNum& lhs, const BigNum& rhs)
{
size_t lsize, rsize;
lsize = lhs.value.size();
rsize = rhs.value.size();
size_t n = lsize > rsize ? lsize : rsize;
BigNum res(n + 1);
res.value[0] = '0';
if( lsize > rsize )
{
Add(lhs, rhs, res);
}
else
{
Add(rhs, lhs, res);
}
return res;
}
//我自己實現(xiàn)的大數(shù)的加法的程序。。 終于驗證可以使用了 呵呵
這個程序?qū)懞昧?也算可以了了我的心愿了的
去年的某個時候 在杭州的UT斯達(dá)康面試 上機(jī)題就是這一道 我死活沒有憋出來,當(dāng)時就很后悔 為什么不好好的看看論壇上的帖子 對上面的問題做做呢?那樣子的話 也許我就不會這么悲慘了,老是在哪里自怨自唉。
總結(jié)起來
我其實是眼高手低,然后從來都被寵著沒有認(rèn)清過自己。小學(xué)初中,老媽老師都說我數(shù)學(xué)學(xué)的還不錯,其實是有點小聰明,分?jǐn)?shù)還是那么可憐的一點點;到高中,因
為學(xué)校比較一般,考的名次看起來很美,被假象迷惑了;大學(xué),因為自己有點基礎(chǔ),被給哥封為軟件最好,也有點沾沾自喜;到了這個公司,也許因為我身體的原
因,也有點面試時做題速度超快的原因,被經(jīng)理說我程序不錯,還是沒有擺正自己的位子。
受點挫折才好。嗯
呵呵, 心態(tài) , 心態(tài)才是一切。
不要眼高手低