diff --git a/include/solution/326.h b/include/solution/326.h new file mode 100644 index 0000000..c53853c --- /dev/null +++ b/include/solution/326.h @@ -0,0 +1,12 @@ +#ifndef INC_326_H +#define INC_326_H +#ifdef __cplusplus +extern "C" +{ +#endif +#include + bool isPowerOfThree(int n); +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/326.c b/src/326.c new file mode 100644 index 0000000..7a80d1a --- /dev/null +++ b/src/326.c @@ -0,0 +1,23 @@ +#define METHOD 2 +#include + +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 +} \ No newline at end of file diff --git a/tests/test_326.cpp b/tests/test_326.cpp new file mode 100644 index 0000000..008cc8b --- /dev/null +++ b/tests/test_326.cpp @@ -0,0 +1,34 @@ +#include +#include + +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的幂 +} \ No newline at end of file