十进制转R进制
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string tentoR(int x, int r) {
if (x == 0) return "0"; // 如果x为0,直接返回"0"
string s;
while (x) {
int num = x % r;
if (num >= 10) s += 'A' + (num - 10); // 处理10及以上的数字转为字母
else s += num + '0'; // 处理0-9的数字
x /= r;
}
reverse(s.begin(), s.end()); // 反转字符串得到正确的顺序
return s;
}
int main() {
int n, r;
cin >> n >> r;
cout << tentoR(n, r);
return 0;
}
计算一个数转为二进制后有几个1
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int calebinone(int x)
{
int cnt = 0;
while (x)
{
cnt++;
x &= x - 1;//每次将最后一个1变为0
}
return cnt;
}
int main()
{
int n;
cin >> n;
cout << calebinone(n);
}
异或(^)相同为0,不同为1
最大公约数和最小公倍数(递归版本)
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int gcd(int a, int b) // 最大公约数
{
return b == 0 ? a : gcd(b, a % b);
}
int lcm(int a, int b) // 最小公倍数
{
return a / gcd(a, b) * b;
}
int main()
{
int a, b;
cin >> a >> b;
cout << "最大公约数是:" << gcd(a, b) << endl;
cout << "最小公倍数是:" << lcm(a, b) << endl;
return 0;
}
日期(闰年)
显示某一年的日历
#include<iostream>
using namespace std;
int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
// 检查是否为闰年
bool check(int year) {
if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
return true;
return false;
}
int main() {
int y;
cin >> y;
// 根据年份调整二月天数
if(check(y))
days[2] = 29;
else
days[2] = 28; // 确保处理多个年份时对于非闰年,二月的天数正确设置为28天
for(int i = 1; i <= 12; i++) { // 十二个月
for(int j = 1; j <= days[i]; j++)
cout << y << "年" << i << "月" <<