GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithm/src/com/BitAlgorithms/Bityunsuan.java at master · KleinHong/algorithm Expand file tree/ Copy pathBityunsuan.javaMore file actions 114 lines (99 loc) · 2.2 KB / Copy pathBityunsuan.javaFile metadata and controls114 lines (99 loc) · 2.2 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 package com.BitAlgorithms; import javax.management.RuntimeErrorException; /** * hzy:jdk1.8 */ /** * @author 残月 * @descripition 仅使用位运算实现加减乘除,不需要考虑数据溢出 * @ieda */ public class Bityunsuan { public static int add(int m,int n) { int tmp=0; while(n!=0) { tmp=m; m=m^n; n=(n&tmp)<<1; } return m; } public static int minus(int m,int n) { return add(m,negNum(n)); } private static int negNum(int n) { // TODO Auto-generated method stub return add(~n,1); } public static int multi(int m,int n) { int res=0; while(n!=0) { if((n&1)==1) { res=add(res,m); } m<<=1; n>>>=1; } return res; } //不适用int最小数,因为最小数的绝对值不能转换成正数 public static int div(int m,int n) { if(n==0) { return Integer.MAX_VALUE; } int res=0; boolean sign=isNeg(m)==isNeg(n); int x=isNeg(m)?m:minus(0,m); int y=isNeg(n)?n:minus(0,n); for(int i=31;i>-1;i=minus(i,1)) { if((x>>i)>=y) { res|=(1<<i); x=minus(x,y<<i); } } return sign?res:multi(res, -1); } // public static int div(int m,int n) { // int x=isNeg(m)?negNum(m):m; // int y=isNeg(n)?negNum(n):n; // int res=0; // for(int i=31;i>-1;i=minus(i,1)) { // if((x>>i)>=y) { // res|=(1<<i); // x=minus(x,y<<i); // } // } // return isNeg(m)^isNeg(n)?negNum(res):res; // // } private static boolean isNeg(int m) { // TODO Auto-generated method stub return m>0; } public static int divide(int m,int n) { if(n==0) { throw new RuntimeException("除数为0"); } if(m==Integer.MIN_VALUE && n==Integer.MIN_VALUE) { return 1; }else if(m==Integer.MIN_VALUE){ int res=div(add(m,1),n); return add(res,div(minus(m,multi(n, res)),n)); }else if(n==Integer.MIN_VALUE) { return 0; }else { return div(m,n); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(add(9, 5)); System.out.println(minus(9,5)); System.out.println(multi(-9,-5)); System.out.println(div(9, Integer.MIN_VALUE)); System.out.println(divide(Integer.MIN_VALUE,9)); } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |