前兩天做了一道題,題目如下(來自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;
}
};