diff options
-rw-r--r-- | check_num_sum_pow3.c | 26 | ||||
-rw-r--r-- | check_num_sum_pow3.py | 29 |
2 files changed, 55 insertions, 0 deletions
diff --git a/check_num_sum_pow3.c b/check_num_sum_pow3.c new file mode 100644 index 0000000..67fe299 --- /dev/null +++ b/check_num_sum_pow3.c @@ -0,0 +1,26 @@ +// 1780. Check if Number is a Sum of Powers of Three +#include "leetcode.h" + +/* + * given an integer 'n', return true if it is possible to represent 'n' as the + * sum of distinct powers of three. otherwise, return false. an integer 'y' is a + * power of three if there exists an integer 'x' such that 'y == 3^x' + */ + +bool checkPowersOfThree(int n) { + static int pow3[] = {4782969, 1594323, 531441, 177147, 59049, + 19683, 6561, 2187, 729, 243, + 81, 27, 9, 3, 1}; + for (int i = 0; i < 15; i++) + if (n >= 2 * pow3[i]) + return false; + else if (n >= pow3[i]) + n -= pow3[i]; + return true; +} + +int main() { + printf("%d\n", checkPowersOfThree(12)); // expect: 1 + printf("%d\n", checkPowersOfThree(91)); // expect: 1 + printf("%d\n", checkPowersOfThree(21)); // expect: 0 +} diff --git a/check_num_sum_pow3.py b/check_num_sum_pow3.py new file mode 100644 index 0000000..b931e50 --- /dev/null +++ b/check_num_sum_pow3.py @@ -0,0 +1,29 @@ +# 1780. Check if Number is a Sum of Powers of Three + +""" +given an integer 'n', return true if it is possible to represent 'n' as the +sum of distinct powers of three. otherwise, return false. an integer 'y' is a +power of three if there exists an integer 'x' such that 'y == 3^x' +""" + + +class Solution(object): + def checkPowersOfThree(self, n): + """ + :type n: int + :rtype: bool + """ + pow3 = [3**i for i in reversed(range(15))] + for i in pow3: + if n >= 2 * i: + return False + elif n >= i: + n -= i + return True + + +if __name__ == "__main__": + obj = Solution() + print(obj.checkPowersOfThree(12)) + print(obj.checkPowersOfThree(91)) + print(obj.checkPowersOfThree(21)) |