寒假每日练习:数学基础

今天写的比较少,主要是写着写着就睡着了,主要是数学基础中的进制问题:P1143,P1469,P1017主要讲一下后俩道题,第一题就直接放代码了:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <stack>

using namespace std;
int n1, n2;
string a;
stack <char> ans;
int Get_num(char str)
{
	if (str >= '0' && str <= '9')
	{
		return str - '0';
	}
	else {
		return str - 'A' + 10;
	}
}

char Get_str(int x)
{
	if (x >= 0 && x <= 9)
	{
		return char(x + '0');
	}
	else {
		return char(x - 10 + 'A');
	}
}

int main()
{
	cin >> n1 >> a >> n2;
	int num = 0;
	for (int i = 0; i < a.size(); i++)
	{
		num += Get_num(a[a.size()-1-i]) * pow(n1, i);
	}
	int tmp = n2;
	while (num != 0)
	{
		int tm = num % tmp;
		num = num / tmp;
		ans.push(Get_str(tm));
	}
	while (!ans.empty())
	{
		cout << ans.top();
		ans.pop();
	}

	return 0;
}

P1469主要是得知道有个性质:

那结果就是所有数的异或了:

#include<cstdio>
int x, n, ans;
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &x), ans ^= x;
    printf("%d\n", ans);
}

P1017最重要的一点就是处理余数是负数的情况,这个时候减一个除数就能保证是正数了:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <stack>
using namespace std;

int num, n;
stack <char> ans;
int main()
{
	cin >> num >> n;
	cout << num << '=';
	while (num != 0)
	{
		int tm = num % n;
		if (tm < 0)
		{
			tm = tm - n;
			num += n;
		}
		num = num / n;
		if (tm >= 0 && tm <= 9)
		{
			ans.push(tm + '0');
		}
		else {
			ans.push(tm - 10 + 'A');
		}
	}
	
	while (!ans.empty())
	{
		cout << ans.top();
		ans.pop();
	}
	cout << "(base" << n << ')';
	return 0;
}

  • 17
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值