//加法 public static int add(int a, int b) { int ans; while(b!=0) { ans = a^b; b = ((a&b)<<1); a = ans; } return a; } //减法 public static int sub(int a, int b) { return add(a, -b); } //正数乘法 private static int posMultiply(int a,int b) { int ans = 0; while(b>0) { if((b&0x1)==1)ans = add(ans, a); a = (a<<1); b = (b>>1); } return ans; } //乘法 public static int multiply(int a,int b) { if(a==0||b==0)return 0; if(a>0 && b>0) return posMultiply(a, b); if(a<0) { if(b<0) { return posMultiply(-a, -b); } else { return -posMultiply(-a, b ); } } else { return -posMultiply(a, -b); } } //正数除法 private static int posDiv(int x,int y) { int ans=0; for(int i=31;i>=0;i--) { if((x>>i)>=y) { ans+=(1<<i); x-=(y<<i); } } return ans; } //除法 public static int div( int a, int b ) { assert(b!=0); if(a==0)return 0; if(a>0) { if(b>0) { return posDiv(a,b); } else { return -posDiv( a,-b); } } else { if(b>0) { return -posDiv(a, b); } else { return -posDiv(-a, -b); } } } //求负数 public static int negtive(int a) { return add(~a, 1); } //比较正数大小 private static boolean isbigerPos( int a, int b ) { int c = 1; b = (a^b); if(b==0)return false; while(b>0) { b>>=1; c <<= 1; } return (c&a)==0; } //比较大小 public static boolean isbiger( int a, int b ) { if(a<0) { if(b<0) { return isbigerPos( negtive(b), negtive(a) ); } else { return false; } } else { if(b<0) { return true; } else { return isbigerPos(a, b); } } } public static int divideby3(int x) { int sum = 0; while(x > 3) { sum = add(x>>2 , sum); x = add(x>>2 , x&3); } if(x == 3) { sum = add(sum , 1); } return sum; } public static void main(String[] args) { System.out.println(add(13,19)); System.out.println(sub(13,19)); System.out.println(multiply(13,19)); System.out.println(div(10,5)); System.out.println(negtive(13)); System.out.println(isbiger(10,5)); System.out.println(isbiger(10,11)); System.out.println(divideby3(15)); System.out.println(divideby3(14)); System.out.println(divideby3(13)); System.out.println(divideby3(12)); System.out.println(divideby3(11)); }