1290
This commit is contained in:
12
include/solution/1290.h
Normal file
12
include/solution/1290.h
Normal file
@@ -0,0 +1,12 @@
|
||||
#ifndef INC_1290_H
|
||||
#define INC_1290_H
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
#include <ListNode.h>
|
||||
int getDecimalValue(struct ListNode *head);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
12
src/1290.c
Normal file
12
src/1290.c
Normal file
@@ -0,0 +1,12 @@
|
||||
#include <solution/1290.h>
|
||||
|
||||
int getDecimalValue(struct ListNode *head)
|
||||
{
|
||||
int x = 0;
|
||||
while (head)
|
||||
{
|
||||
x = (x << 1) + head->val;
|
||||
head = head->next;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
48
tests/test_1290.cpp
Normal file
48
tests/test_1290.cpp
Normal file
@@ -0,0 +1,48 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <solution/1290.h>
|
||||
|
||||
class GetDecimalValueTest : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
// 构建链表:vector -> ListNode*
|
||||
ListNode *buildList(const std::vector<int> &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);
|
||||
}
|
||||
Reference in New Issue
Block a user