[英]convert binary to decimal using single linked list and recursive method in java
我們如何使用Java中的單個鏈表和遞歸方法將二進制轉換為十進制? :-s
例如:
輸入: 1-> 0-> 0-> NULL
輸出 4
遞歸有點棘手,因為您需要根據列表長度縮放“較早”的值,最簡單的方法似乎是通過附加參數將結果“到目前為止”傳遞。
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);
}
}
試試這個(列表末尾沒有null):
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);
}
請注意,它將清除列表。
我可以想到兩種解決方法:
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);
如果我們不想計算長度,那么我們可以有一個可以全局訪問的sum變量,
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;
}
}
希望對您有幫助。
由於您沒有告訴您有關鏈表的任何信息,因此我認為它類似於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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.