使用加法、減法以及一位來實現乘除法

用+,-, <<, >>來實現 *, / 。 


package com.pande.jobhunt.problem;
//用+,-, <<, >>來實現 *, / 。
public class ImplemeneMultiAndDevideUsingPlusAndShift {
 public static long multiply(long a, long b) {
  long result = 0;
  long poistive = 1;
  if (a < 0) {
   a = -a;
   poistive = -poistive;
  }
  if (b < 0) {
   b = -b;
   poistive = -poistive;
  }
  long remain = 0;
  while (b > 0) {
   remain = b % 2;
   result += a * remain;
   b = b >> 1;
   a = a << 1;
  }
  return poistive * result;
 }
 // a / b
 public static long divide(long a, long b) {
  long result = 0;
  long poistive = 1;
  if (a < 0) {
   a = -a;
   poistive = -poistive;
  }
  if (b < 0) {
   b = -b;
   poistive = -poistive;
  }
  while (a >= b) {
   long d = 1;
   long c = b;
   while (c <= a) {
    a = a - c;
    result += d;
    c <<= 1;
    d <<= 1;
   }
  }
  return poistive * result;
 }
 public static void main(String[] args) {
  long t = multiply(-5, -6);
  System.out.println(t);
  long n = divide(71, 5);
  System.out.println(n);
 }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章