2014-03-07 58 views
0

我试图用Java实现Booth算法,但在我的multiply()函数中忽略算术右移函数(rightShift())。是因为我用product变量的字符串吗?这里是我的代码: -为展位算法实现算术右移

import java.util.Scanner; 
class BoothsAlgorithm{ 
    static String appendZeros(int n){ 
     String result = ""; 
     for(int i = 0; i < n; i++) result += "0"; 
     return result; 
    } 
    static String rightShift(String str){ 
     String result = ""; 
     for(int i = 0; i < str.length(); i++){ 
      if(i == 0) result += str.charAt(i); 
      else result += str.charAt(i-1); 
     } 
     return result; 
    } 
    static String add(String a, String b){ 
     String result = ""; 
     char carry = '0'; 
     for(int i = a.length()-1; i >= 0; i--){ 
      String condition = "" + a.charAt(i) + b.charAt(i) + carry; 
      switch(condition){ 
       case "000": result = "0" + result; break; 
       case "001": result = "1" + result; carry = '0'; break; 
       case "010": result = "1" + result; break; 
       case "011": result = "0" + result; break; 
       case "100": result = "1" + result; break; 
       case "101": result = "0" + result; break; 
       case "110": result = "0" + result; carry = '1'; break; 
       case "111": result = "1" + result; break; 
      } 
     } 
     return result; 
    } 
    static String multiply(int a, int b){ 
     String op1 = Integer.toBinaryString(a); 
     String op2 = Integer.toBinaryString(b); 
     String negop2 = Integer.toBinaryString(-b); 
     char prev = '0'; 
     String product = appendZeros(64-op1.length())+op1; 
     for(int i = 0; i < 32; i++){ 
      if(i > 0) prev = product.charAt(63); 
      if(product.charAt(63)=='0' && prev == '1'){ 
       String temp = appendZeros(32-op2.length()) + op2 + appendZeros(32); 
       product = add(product, temp); 
      } 
      if(product.charAt(63)=='1' && prev == '0'){ 
       String temp = appendZeros(32-negop2.length()) + negop2 + appendZeros(32); 
       product = add(product, temp); 
      } 
      rightShift(product); 
     } 
     return product.substring(32); 
    } 
    public static void main(String args[]){ 
     Scanner sc = new Scanner(System.in); 
     System.out.print("Enter the first number: "); 
     int operand1 = sc.nextInt(); 
     System.out.print("Enter the second number: "); 
     int operand2 = sc.nextInt(); 
     System.out.println("The multiplication is "+multiply(operand1, operand2)); 
    } 
} 

回答

1

您需要product = rightShift(product);或类似的。 rightShift返回一个包含结果的新String。它不能,也不能更改调用者中由product引用的字符串。