【国庆の礼物 之二】洛谷P1017 进制转换

题目如上。
这题最难的是负数进制的处理,正数进制的处理非常简单,只要不断进行除法即可。由于除法除得的数据是从后往前的,所以我们需要一个栈进行保存数据,然后逆序输出出来。
代码(正数进制)

#include<bits/stdc++.h>
using namespace std;
int n,r;
stack<int>stk;
string s="0123456789ABCDEFGHIJ";
//对于超过10进制进行处理

int main(){
  cin>>n>>r;
  cout<<n<<"=";
  while(n!=0){
    int t=n%r;
    stk.push(t);
    n/=r;
  }
  while(stk.size()!=0){
    cout<<s[stk.top()];
    stk.pop();
  }
  cout<<"(base"<<r<<")";
  return 0;
}

对负数进制的处理:需要更改取模的算法,使得取模为正数

if(t<0){
      t-=r;n+=r;//对负数进行变换
}

然后这道题就可以AC了

#include<bits/stdc++.h>
using namespace std;
int n,r;
stack<int>stk;
string s="0123456789ABCDEFGHIJ";
//对于超过10进制进行处理

int main(){
  cin>>n>>r;
  cout<<n<<"=";
  while(n!=0){
    int t=n%r;
    if(t<0){
      t-=r;n+=r;//对负数进行变换
    }
    stk.push(t);
    n/=r;
  }
  while(stk.size()!=0){
    cout<<s[stk.top()];
    stk.pop();
  }
  cout<<"(base"<<r<<")";
  return 0;
}

最后祝大家国庆快乐!

相关文章:

  • 2021-08-11
  • 2021-09-01
  • 2021-10-31
  • 2022-01-02
  • 2021-07-29
  • 2021-12-15
  • 2021-11-25
猜你喜欢
  • 2021-12-19
  • 2021-12-12
  • 2022-12-23
  • 2022-12-23
  • 2021-08-17
  • 2021-12-23
  • 2022-03-02
相关资源
相似解决方案