uint.h

来自「一个我的数据结构解题集合」· C头文件 代码 · 共 92 行

H
92
字号
#ifndef UINT_H__
#define UINT_H__

#include <stdexcept>
#include "Vector.h"


struct Digit {		// 十进制数值位

	typedef unsigned char Value;	// 存放值的类型

	enum { BASE = 10 };

	/* 默认构造函数
	 */
	Digit()
		: val(0) {}

	/* 带单参数的构造函数
	 * v: 值
	 */
	explicit Digit(Value v)
		: val(v) {}

	/* 将val修剪到 [0, BASE) 范围内
	 * 返回进位值
	 */
	Value trim() {
		Value carry = val/BASE;
		val %= BASE;

		return carry;
	} // trim()

	Value val;		// 数值

}; // Digit


class UInt {		// 无限长无符号整数
private:
	Vector<Digit> vec_;			// 内部表示: Digit类型的动态数组
public:

	/* 默认构造函数
	 */
	UInt() {}

	/* 构造函数: 通过字符串ch构造整数
	 *           若字符串ch==0或者不代表无符号整数, 抛出std::invalid_argument
	 */
	explicit UInt(const char *ch);

	/* 拷贝构造函数
	 */
	UInt(const UInt& that) 
		: vec_( that.vec_ ) {}

	/* 赋值函数
	 */
	UInt& operator=(const UInt& that) {
		vec_ = that.vec_;
		return *this;
	} // operator=(const UInt&)


	/* 本整数值加上rhs
	 */
	void add(const UInt& rhs);


	/* 本整数值乘以十进制位e
	 * 要求: e的值必须是 [0, Digit::BASE) 的整数
	 *       违反则抛出std::invalid_argument
	 */
	void mul(Digit e);


	/* 本整数值乘以整数值rhs
	 */
	void mul(const UInt& rhs);


	/* 在cout打印该无符号整数
	 */
	void print() const;


}; // UInt


#endif // UINT_H__

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?