题目:进制转换(蓝桥OJ 1230)

题目:

解题思路:

        N转M进制需要有一个中间转换,就是转十进制 

题解:

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1000;
int a[N];//写一个数组接s的数据

char ch[] = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C','D', 'E', 'F'};//十六进制的0~15



void solve()
{
  int n, m;cin >> n >> m;
  string s; cin >> s;
  int len = s.length();
  s = "#" + s;//将s[0]为#,方便当从一开始遍历的操着
  for(int i = 1; i <= len; i++)//将字符转换为得到n进制的数字
  {
    if('0' <= s[i] && s[i] <= '9')a[i] = s[i] - '0';
    else a[i] = s[i] - 'A' + 10;
  }


  ll x = 0;
  for(int i = 1; i <= len; i++)x = x * n + a[i];//k进制转10进制

  string ans;//将10进制转k进制模板
  while(x)
  {
    ans += ch[x % m];
    x /= m;
  }
  reverse(ans.begin(), ans.end());
  cout << ans<< '\n';

  
}
int main()
{
 ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
 int _;cin >> _;
 while(_--)solve();//#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1000;
int a[N];//写一个数组接s的数据

char ch[] = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C','D', 'E', 'F'};//十六进制的0~15



void solve()
{
  int n, m;cin >> n >> m;
  string s; cin >> s;
  int len = s.length();
  s = "#" + s;//将s[0]为#,方便当从一开始遍历的操着
  for(int i = 1; i <= len; i++)//将字符转换为得到n进制的数字
  {
    if('0' <= s[i] && s[i] <= '9')a[i] = s[i] - '0';
    else a[i] = s[i] - 'A' + 10;
  }


  ll x = 0;
  for(int i = 1; i <= len; i++)x = x * n + a[i];//k进制转10进制

  string ans;//将10进制转k进制模板
  while(x)
  {
    ans += ch[x % m];
    x /= m;
  }
  reverse(ans.begin(), ans.end());
  cout << ans<< '\n';

  
}
int main()
{
 ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
 int _;cin >> _;
 while(_--)solve();//N转M进制需要有一个中间转换,就是转十进制
 return 0;

}
 return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值