gpt4 book ai didi

java - Java 中的二进制到 Int 链表

转载 作者:行者123 更新时间:2023-12-01 11:34:26 25 4
gpt4 key购买 nike

我创建了一个链接列表,它将二进制数存储在字符串中,并将其转换为单个位并存储在每个链接中。我的问题是我已经完成了所有这些,现在我正在尝试创建一种方法来获取这些位并将其转换为整数。

问题是二进制到整数的逻辑无法正常工作。例如:如果我输入一个二进制值 00000001 我会很好地打印出我的列表 0|0|0|0|0|0|0|1 但我的整数总数是当它应该是“1”时返回为“0”

我的主要方法

    private  static Scanner input =new Scanner (System.in);

public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList LL=new LinkedList();

char c=' ';
int i=0;
int total=0;

System.out.println("Enter a 8-Bit Binary Number");
String s=input.next();

if(s.length()<8 ||s.length()>8 || s.length()<0 || s.length()==0){
System.out.println("Error");
}

while(i<s.length()){//start while : breaks string into single bits and stores into a link individually
c=s.charAt(i);
LL.addfromTail(new LinkData(c));
LL.BinarytoInt(new LinkData(c));
i++;
}//end while

LL.PrintList();
System.out.println();

我的LinkedList类

             public class LinkedList {
Link head=null;
int total=0;




void PrintList(){//start method
Link curr=head;

while(curr!=null){//start while
System.out.print(curr.ld+"|");
curr=curr.next;
}//end while
}//end method



void addfromHead(LinkData n){//start method

Link nl=new Link(n);
if(head==null){
head=nl;
}

else{
nl.next=head;
head=nl;
}
}//end method



void addfromTail(LinkData n){
Link nl=new Link(n);

if(head==null){
head=nl;
}
else{
Link curr=head;
while(curr.next!=null){
curr=curr.next;
}
curr.next=nl;
}
}



/* int BinarytoInt(LinkData ld2){
Link curr=new Link(ld2);
curr=head;
int x=1;
while(curr.next!=null){
if(curr.ld.binarybit=='1'){
total=total+(x*1);
}
x=x*2;
curr=curr.next;
}//end while
System.out.println(total);
return total;
}
*/



/*void BinarytoInt(char c){

Link curr=head;

int value=128;

while(curr.next!=null){
if(c=='1'){
total=total+(value*1);
curr=curr.next;
}//end if

value=value/2;
}//end while

System.out.println(total);
}*/







}

最佳答案

看起来问题在于您使用单个临时节点调用 BinarytoInt(),而不是遍历整个 LinkedList

只需在方法开头将 curr 设置为 head 即可,无需使用临时节点作为参数:

//Remove parameter, it's not needed:
void BinarytoInt(){
int x=128; int i=0;int total=0;
//Link curr=new Link(temp);
Link curr = head; //set curr to head reference

while(curr.next!=null){
if(curr.ld.binarybit=='1'){
//total=total+(x*1); //this is fine
total += x; //more elegant
}
curr=curr.next;
x=x/2;
}//end while
System.out.println(total);
}//end method

然后,不要在每次迭代时调用 BinarytoInt(),而是在填充整个列表后执行此操作。为了使 2 的每个倍数与每个列表项正确对齐,这是必要的:

while(i<s.length()){
c=s.charAt(i);
LL.addfromTail(new LinkData(c));
//LL.BinarytoInt(new LinkData(c)); //remove this
i++;
}//end while

LL.BinarytoInt(); //Do this after the list is populated

LL.PrintList();
System.out.println();

关于java - Java 中的二进制到 Int 链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30148531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com