Skip to content

Commit 47b4886

Browse files
committed
1780. Check if Number is a Sum of Powers of Three: AC
1 parent e092e54 commit 47b4886

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1341,3 +1341,4 @@ mod s1774_closest_dessert_cost;
13411341
mod s1775_equal_sum_arrays_with_minimum_number_of_operations;
13421342
mod s1776_car_fleet_ii;
13431343
mod s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate;
1344+
mod s1780_check_if_number_is_a_sum_of_powers_of_three;
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* [1780] Check if Number is a Sum of Powers of Three
3+
*
4+
* Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.
5+
* An integer y is a power of three if there exists an integer x such that y == 3^x.
6+
*
7+
* Example 1:
8+
*
9+
* Input: n = 12
10+
* Output: true
11+
* Explanation: 12 = 3^1 + 3^2
12+
*
13+
* Example 2:
14+
*
15+
* Input: n = 91
16+
* Output: true
17+
* Explanation: 91 = 3^0 + 3^2 + 3^4
18+
*
19+
* Example 3:
20+
*
21+
* Input: n = 21
22+
* Output: false
23+
*
24+
*
25+
* Constraints:
26+
*
27+
* 1 <= n <= 10^7
28+
*
29+
*/
30+
pub struct Solution {}
31+
32+
// problem: https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/
33+
// discuss: https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/discuss/?currentPage=1&orderBy=most_votes&query=
34+
35+
// submission codes start here
36+
37+
impl Solution {
38+
pub fn check_powers_of_three(n: i32) -> bool {
39+
let mut temp = n;
40+
41+
while temp > 0 {
42+
if temp % 3 == 2 {
43+
return false;
44+
}
45+
temp /= 3;
46+
}
47+
48+
true
49+
}
50+
}
51+
52+
// submission codes end
53+
54+
#[cfg(test)]
55+
mod tests {
56+
use super::*;
57+
58+
#[test]
59+
fn test_1780_example_1() {
60+
let n = 12;
61+
62+
let result = true;
63+
64+
assert_eq!(Solution::check_powers_of_three(n), result);
65+
}
66+
67+
#[test]
68+
fn test_1780_example_2() {
69+
let n = 91;
70+
71+
let result = true;
72+
73+
assert_eq!(Solution::check_powers_of_three(n), result);
74+
}
75+
76+
#[test]
77+
fn test_1780_example_3() {
78+
let n = 21;
79+
80+
let result = false;
81+
82+
assert_eq!(Solution::check_powers_of_three(n), result);
83+
}
84+
}

0 commit comments

Comments
 (0)