A+B问题

给出两个整数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));
	}

}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值