diff --git a/include/solution/1290.h b/include/solution/1290.h new file mode 100644 index 0000000..4ffc2ba --- /dev/null +++ b/include/solution/1290.h @@ -0,0 +1,12 @@ +#ifndef INC_1290_H +#define INC_1290_H +#ifdef __cplusplus +extern "C" +{ +#endif +#include + int getDecimalValue(struct ListNode *head); +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/src/1290.c b/src/1290.c new file mode 100644 index 0000000..809079e --- /dev/null +++ b/src/1290.c @@ -0,0 +1,12 @@ +#include + +int getDecimalValue(struct ListNode *head) +{ + int x = 0; + while (head) + { + x = (x << 1) + head->val; + head = head->next; + } + return x; +} \ No newline at end of file diff --git a/tests/test_1290.cpp b/tests/test_1290.cpp new file mode 100644 index 0000000..324d75d --- /dev/null +++ b/tests/test_1290.cpp @@ -0,0 +1,48 @@ +#include +#include + +class GetDecimalValueTest : public ::testing::Test +{ + protected: + // 构建链表:vector -> ListNode* + ListNode *buildList(const std::vector &values) + { + ListNode dummy{0, nullptr}; + ListNode *current = &dummy; + for (int v : values) + { + current->next = new ListNode{v, nullptr}; + current = current->next; + } + return dummy.next; + } + + // 释放链表 + void freeList(ListNode *head) + { + while (head) + { + ListNode *tmp = head; + head = head->next; + delete tmp; + } + } +}; + +// 示例 1: [1, 0, 1] → 5 +TEST_F(GetDecimalValueTest, Binary101) +{ + ListNode *head = buildList({1, 0, 1}); + int expected = 5; + EXPECT_EQ(getDecimalValue(head), expected); + freeList(head); +} + +// 示例 2: [0] → 0 +TEST_F(GetDecimalValueTest, Binary0) +{ + ListNode *head = buildList({0}); + int expected = 0; + EXPECT_EQ(getDecimalValue(head), expected); + freeList(head); +} \ No newline at end of file