326
This commit is contained in:
12
include/solution/326.h
Normal file
12
include/solution/326.h
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
#ifndef INC_326_H
|
||||||
|
#define INC_326_H
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C"
|
||||||
|
{
|
||||||
|
#endif
|
||||||
|
#include <stdbool.h>
|
||||||
|
bool isPowerOfThree(int n);
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
23
src/326.c
Normal file
23
src/326.c
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
#define METHOD 2
|
||||||
|
#include <solution/326.h>
|
||||||
|
|
||||||
|
bool isPowerOfThree(int n)
|
||||||
|
{
|
||||||
|
#if METHOD == 1
|
||||||
|
if (n <= 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
while (n != 1)
|
||||||
|
{
|
||||||
|
if (n % 3 != 0)
|
||||||
|
return false;
|
||||||
|
n /= 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
#elif METHOD == 2
|
||||||
|
// 在题目给定的 32 位有符号整数的范围内,最大的 3 的幂为 3^19 = 1162261467。
|
||||||
|
// 我们只需要判断 n 是否是 3^19 的约数即可。
|
||||||
|
return n > 0 && 1162261467 % n == 0;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
34
tests/test_326.cpp
Normal file
34
tests/test_326.cpp
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <solution/326.h>
|
||||||
|
|
||||||
|
class IsPowerOfThreeTest : public ::testing::Test
|
||||||
|
{
|
||||||
|
protected:
|
||||||
|
void AssertIsPowerOfThree(int input, bool expected)
|
||||||
|
{
|
||||||
|
EXPECT_EQ(isPowerOfThree(input), expected);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 示例测试用例
|
||||||
|
TEST_F(IsPowerOfThreeTest, ExampleTrueCases)
|
||||||
|
{
|
||||||
|
AssertIsPowerOfThree(27, true);
|
||||||
|
AssertIsPowerOfThree(9, true);
|
||||||
|
AssertIsPowerOfThree(1, true); // 3^0 = 1
|
||||||
|
AssertIsPowerOfThree(3, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(IsPowerOfThreeTest, ExampleFalseCases)
|
||||||
|
{
|
||||||
|
AssertIsPowerOfThree(0, false);
|
||||||
|
AssertIsPowerOfThree(45, false);
|
||||||
|
AssertIsPowerOfThree(-3, false);
|
||||||
|
AssertIsPowerOfThree(10, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(IsPowerOfThreeTest, EdgeCases)
|
||||||
|
{
|
||||||
|
AssertIsPowerOfThree(INT_MIN, false);
|
||||||
|
AssertIsPowerOfThree(INT_MAX, false); // INT_MAX = 2^31 - 1,不是3的幂
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user