@ltd em mới học java nên đang gà lắm. chỉ mới biết thế này thôi
http://ideone.com/otClJP
package oop.asg02;
import java.io.IOException;
public class BigInteger
{
private String s;
public BigInteger(long init) {
s = String.valueOf(init);
}
public BigInteger(String init) throws IOException {
if (init == "")
s = "0";
else s = init;
while (s.charAt (0) == '0' && s.length() > 1)
s = s.substring (1);
for(int i=0; i<init.length(); i++){
if(init.charAt(i)< '0' | init.charAt(i)> '9'){
throw new IOException ();
}
}
}
public String toString() {
return s;
}
public boolean equals(Object other) {
return toString().equals(other.toString());
}
public long toLong() {
return Long.parseLong(s);
}
public BigInteger add(BigInteger other)throws IOException {
while(this.s.length()>other.s.length()){
other.s = "0" + other.s;
}
while(this.s.length()<other.s.length()){
s = "0" + s;
}
String result = "";
int remember = 0, temp = 0;
for(int i = s.length()- 1;i >= 0;i--){
temp = (int)(s.charAt(i)-'0') + (int)(other.s.charAt(i)-'0') + remember;
if(temp >=10){
temp = temp % 10;
remember = 1;
}
else{
remember = 0;
}
result = Integer.toString(temp) + result;
}
if(remember == 1){
result = '1' + result ;
}
return new BigInteger(result);
}
public int compareTo(BigInteger other){
if(this.s.length() < other.s.length())
return -1;
if(this.s.length() > other.s.length())
return 1;
if(this.s.length() == other.s.length()){
for(int i=0; i<this.s.length(); i++){
if(this.s.charAt(i) < other.s.charAt(i))
return -1;
if(this.s.charAt(i) > other.s.charAt(i))
return 1;
}
}
return 0;
}
public BigInteger subtract(BigInteger other)throws IOException {
int remember = 0;
int temp = 0;
String result = new String ();
while(this.s.length()>other.s.length()){
other.s = "0" + other.s;
}
while(this.s.length()<other.s.length()){
s = "0" + s;
}
BigInteger s1 = new BigInteger(s);
if(s1.compareTo(other)==1 || s1.compareTo(other)==0)
{
for(int i = s.length()- 1;i >= 0;i--){
temp = (int)(this.s.charAt(i))-'0' - ((int)(other.s.charAt(i))-'0' + remember);
if(temp <0)
{
temp = (int)(this.s.charAt(i))-'0' + 10 - ((int)(other.s.charAt(i))-'0' + remember);
remember = 1;
}
else{
remember=0;
}
result = Integer.toString(temp) + result;
}
return new BigInteger(result);
}
else{
for(int i = s.length()- 1;i >= 0;i--){
temp = (int)(other.s.charAt(i))-'0' - ((int)(this.s.charAt(i))-'0' + remember);
if(temp <0)
{
temp = (int)(other.s.charAt(i))-'0' + 10 - ((int)(this.s.charAt(i))-'0' + remember);
remember = 1;
}
else{
remember=0;
}
result = Integer.toString(temp) + result;
}
return new BigInteger("-" + result);
}
}
public BigInteger clone(){
BigInteger init = null;
try{
init = new BigInteger(s);
} catch (IOException e){
System.out.println("day co ki tu char!");
}
return init;
}
}