我们如何使用单链表和java中的递归方法将二进制转换为十进制? :-s
例如:
输入: 1-> 0-> 0-> NULL
输出: 4
答案 0 :(得分:0)
递归时有点棘手,因为你需要根据列表长度来缩放“早期”值,最简单的方法似乎是通过一个额外的参数“向前”传递结果。
class Node {
int value;
Node next;
int toDecimal(int resultSoFar) {
int resultSoFar = 2 * resultSoFar + value;
return next == null ? resultSoFar : toDecimal(resultSoFar);
}
int toDecimal() {
toDecimal(0);
}
}
答案 1 :(得分:0)
试试这个(没有列表末尾的空格):
public Integer binToDec(LinkedList<Integer> list){
Double size = (double) list.size();
if(size == 0D) return 0;
Integer number = list.getFirst();
list.removeFirst();
if(number != 0) return binToDec(list) + number*new Double(Math.pow(2D, size - 1)).intValue();
else return binToDec(list);
}
请注意清除列表。
答案 2 :(得分:0)
我可以想出两种解决方法:
1-如果已知列表长度:
// To find length of list
public int length(Node head) {
int count = 0;
while(head != null) {
count++;
head = head.next;
}
return count;
}
public static int convertWhenLengthIsKnown(Node head, int len) {
int sum = 0;
if(head.next != null) {
sum = convertWhenLengthIsKnown(head.next, len-1);
}
return sum + head.data * (int)Math.pow(2,len);
}
// Call this function as below:
convertWhenLengthIsKnown(head, length(head)-1);
如果我们不想计算长度,那么我们可以得到一个全局可访问的和变量,
private static int sum = 0;
public static int convert(Node head,int i) {
if(head.next != null) {
i = convert(head.next, i);
}
sum += head.data * (int)Math.pow(2,i);
return i+1;
}
// Call this function as below:
convert(head,0);
以下是Node类:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
希望它可以帮助你。
答案 3 :(得分:0)
由于您没有说明您的链接列表,我认为它类似于pbajpai21中的Node
类。
在不知道链的长度的情况下,您可以将每个级别的值向左移动一个位置。
列表中每个节点的类
class Node {
int digit;
Node child;
Node(int data) {
this.digit = data;
}
public int getDigit() {
return digit;
}
public void setChild(Node child) {
this.child = child;
}
public Node getChild() {
return child;
}
}
演示课程
public class Bits {
public static void main(String[] args) {
int[] ints = new int[] {1, 0, 1, 0, 1, 0};
Node parent = new Node(ints[0]);
Node root = parent;
for (int i = 1; i < ints.length; i++) {
Node child = new Node(ints[i]);
parent.setChild(child);
parent = child;
}
long value = computeValue(0, root);
System.out.println();
System.out.println("value = " + value);
}
private static long computeValue(long parentValue, Node node) {
if (node == null) {
return parentValue;
}
// only to print the current digit
System.out.print(node.getDigit());
long value = (parentValue << 1) + node.getDigit();
return computeValue(value, node.getChild());
}
}
输出
101010
value = 42