class Node{
int num;
Node next;
Node(int n)
{
num=n;
next = null;
}
} //end node
class Q88
{
public static void main (String[] args)
{
Node head1 = toBinary(4);
//print(head1);
Node head2 = toBinary(2);
//print(head2);
double x = addBinaryNumbers(head1, head2);
System.out.println(x);
}//main
public static void print(Node top)
{
while(top!=null)
{
System.out.printf("%d",top.num);
top = top.next;
}
}//end print
public static Node toBinary(int n){
Node np;
Node top = null;
Node last = null;
Node xp= new Node (n);
if (xp.num==0)return xp;
while(n>0){
int x = n%2;
np = new Node(x);
if(top==null)
top = np;
else
last.next = np;
last = np;
n = n/2;
}
return top;
}//end function
public static double toDecimal(Node top){
int c = 0;
double result = 0;
int ans = 0;
double y = Math.pow(2,2);
while(top!=null)
{
result = result + (Math.pow(2,c)*top.num);
c++;
top = top.next;
}
return result;
}//toDecimal
public static double addBinaryNumbers(Node top1, Node top2)
{
//declaration of variables
int sum = 0;
int carry = 0;
int result = 0;
double res = 0.0;
Node tail = null;
Node last = null;
Node ans = null;
boolean ape = true ;
while(top1!=null || top2!=null)
{
sum = top1.num + top2.num + carry;
System.out.println("sum" + sum);
carry = 0;//clear carry before next calculation
if (sum==1 || sum == 0)
{
//System.out.println("ssssuur"+sum);
Node ncar = new Node (sum);
if (tail==null)tail = ncar;
else
last.next = ncar;
last = ncar;
}else{
ans = toBinary(sum);
result = ans.num;
Node x = ans.next;
carry = x.num;
Node ncar = new Node (result);
if (tail==null)tail = ncar;
else
last.next = ncar;
last = ncar;
}//end if;
if ( top1.next !=null && top2.next==null)
{
top1 = top1.next;
System.out.println("ddddddddddddd" + top1.num);
}
//get to end and both numbers are the same
if (top1.next==null && top2.next==null && carry==1)
{
System.out.println("carrrrrrrrrrrrrr"+carry);
Node car = new Node (carry);
if (tail==null)tail = car;
else
last.next = car;
last = car;
}//end if
if ( top2.next !=null && top1.next ==null)
{
top2 = top2.next;
System.out.println("vvvvvvvvvvvv" + top2.num);
}
if ( top1!=null && top2 != null)
{
System.out.println("brian");
top1 = top1.next;
top2 = top2.next;
}
}//while
/*
while(tail!=null)
{
System.out.println("tail "+tail.num);
tail = tail.next;
}
*/
res = toDecimal(tail); //have to send head/top
return res;
}//addBinaryNumbers
}//class
我将十进制数转换为二进制,和他们一起加入。例如,我添加4和2。当值转换为二进制数字逆转,例如,4 = 001 2 = 01。该项目工程,如果我输入两个数字相同(6,6),它给出了正确的答案,但如果我输入两个不同的电话号码(4,2),我得到一个错误。
该项目工程这点
TOP1 = 001
TOP2 = 01
0 = 0(正确)
0 1 = 1(正确)
}除最后1 {BR
{C}上述检查结构,TOP1和TOP2是空(没有值)。我可以得到在top1.num数量(1)总结= top1.num top2.num进行,所以,我不能在最后加上1到完成答案。
答案返回2(不正确)
请帮帮忙!