Leetcode 1290

前兩天做了一道題,題目如下(來自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;
    }
};
發佈了38 篇原創文章 · 獲贊 87 · 訪問量 7303
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章