前两天做了一道题,题目如下(来自leetcode):
题目并不是很难,不过走了点弯路。一开始直觉就是反转链表,这样才能判断出某一位要乘2的多少次方,于是写了如下代码:
class Solution {
public:
int getDecimalValue(ListNode* head) {
int res = 0;
ListNode *pre = NULL;
ListNode *cur = head;
while(cur)
{
ListNode *next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
cur = pre;
int t = 1;
while(cur)
{
res += (t*cur->val);
t *= 2;
cur = cur->next;
}
return res;
}
};
后来其实发现并没有必要,就类似于给你一个10进制的字符串,把它转化为int型整数,没必要反着写,直接从高位到低位计算即可(一开始的自己好蠢),代码如下:
class Solution {
public:
int getDecimalValue(ListNode* head) {
ListNode *cur = head;
int res = 0;
while(cur)
{
res = res*2 + cur->val;
cur = cur->next;
}
return res;
}
};