LeetCode algorithm solution to a problem 1290- binary integer transfer list

Title Description

answer:

I am a direct reversal of the list , and then follow the binary and decimal conversion relationship of demand, in fact, there are many ways.

Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        ListNode* head2 = reverse(head);
        int sum = 0; int tmp = 0;
        while(head2)
        {
            sum += head2->val * pow(2,tmp++);
            head2 = head2->next;
        }
        return sum;
    }

    ListNode* reverse(ListNode* head)
    {
        if(head == NULL || head->next == NULL)
        {
            return head;
        }
        ListNode* res = reverse(head->next);
        head->next->next = head;
        head->next = NULL;
        return res;
    }
};
He published 197 original articles · won praise 18 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_41708792/article/details/104618961