You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this so that the resulting number is a power of two.
Example 1:
Input: n = 1
Output: true
Example 2:
Input: n = 10
Output: false
Constraints:
- 1 <= n <= 109
因为 n 小于 10 的 9 次方, 换算成 2 的次幂就是小于 2 的 32 次方, 也就是我们只需要检查 32 个数字就可以了(即 2 的 0 次方、2 的 1 次方、2 的 2 次方、2 的 3 次方…2 的 31 次方), 因为是重新排序, 所以我们只需要统计每个数字的出现次数就可以了
use std::collections::HashMap;
impl Solution {
pub fn reordered_power_of2(mut n: i32) -> bool {
let mut digits = HashMap::new();
while n > 0 {
*digits.entry(n % 10).or_insert(0) += 1;
n /= 10;
}
'outer: for i in 0..32 {
let mut n = 2i32.pow(i);
let mut ds = HashMap::new();
while n > 0 {
*ds.entry(n % 10).or_insert(0) += 1;
n /= 10;
}
if digits.len() != ds.len() {
continue;
}
for (k, v) in ds {
if let Some(&vv) = digits.get(&k) {
if v != vv {
continue 'outer;
}
continue;
}
continue 'outer;
}
return true;
}
false
}
}

本文介绍了一种判断整数是否能通过重新排列其数字成为2的幂的方法。通过统计每个数字出现的频率,并与2的0到31次幂进行比较,实现高效验证。
1073

被折叠的 条评论
为什么被折叠?



