【发布时间】:2018-04-15 02:57:56
【问题描述】:
我正在尝试在 add(DNumber b) 方法中添加两个 DNumber 对象。关键是能够进行二进制算术。元素正常存储。我应该如何处理不均匀的 ArrayLists?用 0 填充元素较少的那个?那么我应该如何检索每个元素?还有什么是在不使用转换为十进制方法的情况下转换为十进制的好方法:
public class DNumber{
ArrayList<Digit> binary = new ArrayList<Digit>();
/**
* Constructor for objects of class DNumber
*/
public DNumber()
{
Digit num = new Digit(0);
binary.add(num);
}
public DNumber(int val){
int num = val;
if(num > 0){
while (num > 0){
Digit bin = new Digit(num%2);
num /= 2;
binary.add(0, bin);
}
}
else{
Digit bin = new Digit(0);
binary.add(0,bin);
}
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public String toString(){
String s = "";
for(Digit d : binary){
s = s + d.toString();
}
return s;
}
public void add(DNumber b){
int ArraySize1 = binary.size() -1;
int ArraySize2 = b.binary.size() -1;
}
public void toDecimal(){
/**
*
* String s = "";
int result = 0;
int power = 0;
for(Digit d : binary){
s = s + d.toString();
result = Integer.parseInt(s);
}
*/
}
}
public class Digit {
int x = 0;
/**
* Constructor for objects of class Digit
*/
public Digit(int val) {
if (val != 0 && val != 1) {
System.out.println("Error Must be either 1 or 0");
x = 0;
} else {
x = val;
}
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public int getValue() {
return x;
}
public void setValue(int num) {
if (num != 0 && num != 1) {
System.out.println("Error Must be either 1 or 0");
System.out.println("Old Value Retained");
} else {
x = num;
}
}
public String toString() {
return Integer.toString(x);
}
public Digit add(Digit b) {
int returnInt = getValue() + b.getValue();
Digit carry = new Digit(0);
if (returnInt == 2) {
carry = new Digit(1);
setValue(0);
} else if (returnInt == 1) {
carry = new Digit(0);
setValue(1);
} else if (returnInt == 0) {
carry = new Digit(0);
setValue(0);
}
return carry;
}
public Digit add(Digit b, Digit c) {
int returnInt = getValue() + b.getValue() + c.getValue();
Digit carry = new Digit(0);
if (returnInt == 2) {
carry = new Digit(1);
setValue(0);
} else if (returnInt == 1) {
carry = new Digit(0);
setValue(1);
} else if (returnInt == 0) {
carry = new Digit(0);
setValue(0);
} else if (returnInt == 3) {
carry = new Digit(1);
setValue(1);
}
return carry;
}
}
【问题讨论】:
-
拥有 Digit 类来强制输入 1 和 0 不一定是坏事,但是在 Digit 类上添加方法并没有多大意义,因为你真的不能处理进位位。我将专注于仅在 DNumber 级别处理 add 并将第 0 个元素设为 0 位可能会使事情变得更容易
标签: java math arraylist binary