1290. [链表]二进制链表转整数
1290. 二进制链表转整数
方法一:模拟“按权展开求和”
例:\((1011)_2 = 1×2^3+0×2^2+1×2^1+1×2^0=(11)_{10}\)
// 执行耗时:1 ms,击败了19.10% 的Java用户
// 内存消耗:36.3 MB,击败了83.14% 的Java用户
class Solution {
public int getDecimalValue(ListNode head) {
List<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
int ans = 0, len = list.size();
for(int i = len - 1; i >= 0; i--){
ans += list.get(len - 1 - i) * Math.pow(2,i);
}
return ans;
}
}
方法二:字符串转二进制数
// 执行耗时:0 ms,击败了100.00% 的Java用户
// 内存消耗:36.3 MB,击败了75.50% 的Java用户
class Solution {
public int getDecimalValue(ListNode head) {
StringBuilder s =new StringBuilder();
//遍历链表获得二进制数
while(head!=null) {
s.append(head.val);
head=head.next;
}
return Integer.valueOf(s.toString(),2);
}
}
方法三:一次遍历转十进制
class Solution {
public int getDecimalValue(ListNode head) {
// List<Integer> list = new ArrayList<>();
int ans = 0;
while(head != null){
ans = ans * 2 + head.val;
head = head.next;
}
// int ans = 0, len = list.size();
// for(int i = len - 1; i >= 0; i--){
// ans += list.get(len - 1 - i) * Math.pow(2,i);
// }
return ans;
}
}

浙公网安备 33010602011771号