// 1290. 二进制链表转整数
// 给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。
// 请你返回该链表所表示数字的 十进制值 。
// 输入:head = [1,0,1]
// 输出:5
// 解释:二进制数 (101) 转化为十进制数 (5)
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
//麻烦
public int getDecimalValue(ListNode head) {
List<Integer> list = new ArrayList<Integer>();
ListNode node = head;
while (node != null) {
list.add(node.val);
node = node.next;
}
int sum = 0;
for (int i = 0; i < list.size(); i++) {
if (!(list.get(i) == 0 && i == list.size() - 1)) {
sum = sum + (new Double(Math.pow(list.get(i) * 2, (int) list.size() - i - 1))).intValue();
}
}
return sum;
}
// 二进制转十进制,标准
public int getDecimalValue2(ListNode head) {
int decimal = 0;
ListNode node = head;
while (node != null) {
decimal = decimal * 2 + node.val;
node = node.next;
}
return decimal;
}
leetcode-1290. 二进制链表转整数
最新推荐文章于 2024-07-19 19:25:43 发布