📄 uint.cpp
字号:
#include <iostream>
#include <ctype.h>
#include "UInt.h"
using namespace std;
/* 构造函数: 通过字符串ch构造整数
* 若字符串ch不代表无符号整数, 抛出std::invalid_argument
*/
UInt::UInt(const char *ch) {
if (ch == 0)
throw std::invalid_argument("UInt::UInt(const char *ch)\n"
"\trequirement ch != 0 violated.\n");
while (*ch != '\0' && isdigit(*ch)) {
vec_.pushFront(Digit(*ch - '0')); // 从char到Digit::Value的隐式转换
++ch;
}
if (*ch != '\0')
throw std::invalid_argument("UInt::UInt(const char *ch)\n"
"\trequirement ch represents a number violated.\n");
} // UInt(const char *)
/* 本整数值加上rhs
*/
void UInt::add(const UInt& rhs) {
Digit::Value carry = 0; // 进位
int ilhs = 0, irhs = 0;
while ( ilhs < vec_.size() &&
irhs < rhs.vec_.size() ) {
vec_[ilhs].val += rhs.vec_[irhs].val + carry;
carry = vec_[ilhs].trim();
++ilhs;
++irhs;
}
while ( irhs < rhs.vec_.size() ) { // 加入剩余的位
Digit d(rhs.vec_[irhs].val + carry);
carry = d.trim();
vec_.pushBack(d);
++irhs;
}
while (carry != 0) { // 处理剩余的进位
Digit d(carry);
carry = d.trim();
vec_.pushBack(d);
}
} // add(const UInt&)
/* 本整数值乘以十进制位e
* 要求: e的值必须是 [0, Digit::BASE) 的整数
* 违反则抛出std::invalid_argument
*/
void UInt::mul(Digit e) {
Digit::Value carry = 0; // 进位
if (e.val >= Digit::BASE)
throw std::invalid_argument("UInt::mul(Digit e):\n"
"\trequirement e.val < Digit::BASE violated.\n");
for (int itor=0; itor < vec_.size(); ++itor) {
vec_[itor].val *= e.val;
vec_[itor].val += carry;
carry = vec_[itor].trim();
}
while (carry != 0) { // 处理剩余的进位
Digit d(carry);
carry = d.trim();
vec_.pushBack(d);
}
} // mul(Digit)
/* 本整数值乘以整数值rhs
*/
void UInt::mul(const UInt& rhs) {
UInt result, temp;
for (int itor=0; itor < rhs.vec_.size(); ++itor) {
temp = *this;
temp.mul(rhs.vec_[itor]);
for (int i=0; i<itor; ++i) {
temp.vec_.pushFront(Digit(0)); // 乘以10
}
result.add(temp);
}
*this = result;
} // mul(const UInt&)
/* 在cout打印该无符号整数
*/
void UInt::print() const {
for (int itor = vec_.size()-1; itor >=0; --itor) {
cout << static_cast<int>(vec_[itor].val);
}
} // print() const
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -