最大公因数:利用辗转相除法,
最小公倍数:将两个数相乘再除以最大公因数即可得到最小公倍数
int gcd(int a,int b){
return b==0?a;gcd(b,a%b);
}
int lcm(int a,int b){
return a*b/gcd(a,b);
}
进制转化(限于10以下)
进制转换类型的题,通常是利用除法和取模(mod)来进行计算,同时也要注意一些细节,如
负数和零。如果输出是数字类型而非字符串,则也需要考虑是否会超出整数上下界。
class Solution {
public:
std::string convertToBaseSize(int num, int size) {
if (num == 0) return 0;
bool is_negative = num < 0;
if (is_negative) num = -num;
std::string ans;
while (num)
{
int a = num / size;
int b = num % size;
ans = std::to_string(b) + ans;
num = a;
}
return is_negative ? "-" + ans : ans;
}
};
阶乘后的零
每个尾部的 0 由 2 × 5 = 10 而来,因此我们可以把阶乘的每一个元素拆成质数相乘,统计有
多少个 2 和 5。明显的,质因子 2 的数量远多于质因子 5 的数量,因此我们可以只统计阶乘结果
里有多少个质因子 5。
class Solution {
public:
int trailingZeroes(int n) {
return n==0?0:n/5+trailingZeroes(n/5);
}
};