#include<bits/stdc++.h>
using namespace std;
//10进制转为目标进制
void show(int num, int target) {
string ans = "";
if(num == 0) {cout<<"0"; return;}
while(num) {
int tmp = num % target;
if(tmp >= 0 && tmp <= 9)
ans += tmp+'0';
else
ans += tmp-10+'a';
num /= target;
}
reverse(ans.begin(), ans.end());
cout<<ans<<endl;
return;
}
//加法
int add(int a, int b) {
int res = a;
while(b) {
int tmp = a;
a = a ^ b;
b = (tmp & b)<<1;
res = a;
}
return res;
}
//减法
int subtraction(int a, int b) {
b = add(~b, 1); //取相反数
int res = add(a, b);
return res;
}
//乘法
int mul(int a, int b) {
bool isNeg = false;
if((a<0 && b>0) || (a>0 && b<0)) {
isNeg = true;
}
if(a < 0) a = add(~a,1);//求出a的绝对值
if(b < 0) b = add(~b,1);//求出b的绝对值
int res = 0;
while(b) {
//当前位 为b的最右边一位
if(b & 1) {
res = add(res, a);
}
a = a<<1;
b = b>>1;
}
if(isNeg) {
res = add(~res, 1);
}
return res;
}
//除法
int divide(int a, int b) {
if(b==0) throw std::runtime_error("Divided can't be zero...");
bool isNeg = false;
if((a<0 && b>0) || (a>0 && b<0)) {
isNeg = true;
}
if(a < 0) a = add(~a,1);//求出a的绝对值
if(b < 0) b = add(~b,1);//求出b的绝对值
int res = 0;
while(a >= b) {
res = add(res, 1);
a = subtraction(a,b);
}
if(isNeg)
res = add(~res, 1);
return res;
}
int main() {
int a = 10, b = 0;
cout<<"a + b = "<<add(a, b)<<endl;
cout<<"a - b = "<<subtraction(a, b)<<endl;
cout<<"a * b = "<<mul(a,b)<<endl;
cout<<"a / b = "<<divide(a,b)<<endl;
return 0;
}
|