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));}}
阅读全文
0 0
- 关于a+++++b问题
- A+B的问题
- A+B问题
- A+B问题acm
- 空行问题A+B
- A+B问题II
- 1.A+B问题
- A+B问题 844
- 有关A+B问题
- A+B问题
- A+B问题
- A-B问题
- ACM-A+B问题
- 1000 A+B问题
- a+b问题.1
- LintCode-A + B 问题
- 题目:A + B 问题
- HDOJ A+B 问题
- 【算法题】最大的奇约数
- java异常分类
- MongoDB基础
- 浏览器兼容问题
- Spring配置组件扫描和自动装配
- A+B问题
- 乘积最大
- 销售系统
- Service的实战:下载的实现
- TF-IDF及其算法
- 可心耳语-属于网络工程师的人声电台(第二期)
- BZOJ4903 [Ctsc2017]吉夫特
- 数据结构-顺序栈解决迷宫问题
- github开源Java项目导入Eclipse