A+B问题

来源:互联网 发布:快压软件 编辑:程序博客网 时间:2024/06/16 18:10

给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

 注意事项

你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。

说明

a和b都是 32位 整数么?

  • 是的

我可以使用位运算符么?

  • 当然可以
样例

如果 a=1 并且 b=2,返回3


本题需要使用位运算来进行,我们不仅进行了加法运算,同时给出减法,乘法,除法的位运算。

import java.util.Scanner;/** *  * 求解a与b的加减乘除,不允许使用运算符,使用位运算。 * @author Dell * */public class Test1 {  public static int aplusb(int a,int b)  {  while(b!=0)   {   int c=a;    a=a^b;   b=(c&b)<<1;   }  return a;  }  public static int aminusb(int a,int b)  {  int c=aplusb(~b,1);  return aplusb(a,c);    }  public static int amultib(int a,int b)  {   int res=0; while(b!=0) { if((b&1)==1) { res=aplusb(res,a); } b=b>>>1; a=a<<1;  }     return res;    }  public static boolean isNeg(int n)  {  return n<0;  }  public static int div(int a,int b)  {  int x= isNeg(a) ? (~a+1):a;  int y= isNeg(b) ? (~b+1):b;  int res=0;  for(int i=31;i>-1;i=aminusb(i,1))  {  if((x>>i)>=y)  {  res|=(1<<i);  x=aminusb(x,(y<<i));  }    }    return isNeg(a)^isNeg(b)?  (~res+1) : res;  }  public static int divide(int a,int b) throws Exception  {  if(b==0)  {  throw new Exception("除数为0");  }  if(a==Integer.MIN_VALUE && b==Integer.MIN_VALUE)  {  return 1;  }  else if(b==Integer.MIN_VALUE)  {  return 0;  }  else if(a==Integer.MIN_VALUE)  {  int res=div(aplusb(a,1),b);  return aplusb(res,div(aminusb(a,amultib(res,b)),b));    }  else  {  return div(a,b);  }    }public static void main(String[] args) throws Exception {Scanner sc=new Scanner(System.in);int a=sc.nextInt();int b=sc.nextInt();      System.out.println(aplusb(a,b));System.out.println(aminusb(a,b));    System.out.println(amultib(a,b));    System.out.println(divide(a,b));}}







原创粉丝点击