Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mirror-reflection.cpp 937 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-06-24 14:48 +08:00 . Update mirror-reflection.cpp
// Time: O(1)
// Space: O(1)
class Solution {
public:
int mirrorReflection(int p, int q) {
// explanation commented in the following solution
return (p & -p) > (q & -q) ? 2 : (p & -p) < (q & -q) ? 0 : 1;
}
};
// Time: O(log(max(p, q))) = O(1) due to 32-bit integer
// Space: O(1)
class Solution2 {
public:
int mirrorReflection(int p, int q) {
const auto lcm = p * q / gcd(p, q);
// let a = lcm / p, b = lcm / q
if (lcm / p % 2 == 1) {
if (lcm / q % 2 == 1) {
return 1; // a is odd, b is odd <=> (p & -p) == (q & -q)
}
return 2; // a is odd, b is even <=> (p & -p) > (q & -q)
}
return 0; // a is even, b is odd <=> (p & -p) < (q & -q)
}
private:
int gcd(int a, int b) {
while (b != 0) {
int tmp = b;
b = a % b;
a = tmp;
}
return a;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助