洛谷试炼场-简单数学问题-负进制

洛谷试炼场-简单数学问题

P1017 进制转换

题解:

本题考察负进制数的转换。
只不过可能在某个数位上出现负数
你要做的就是从上一位借1来
没错 就和减法差不多

代码

#include <iostream>
#include<stack>
#include<string>
using namespace std;
string ch="0123456789ABCDEFGHIJK";
int main()
{
   int n,r;

   while(cin>>n>>r)
   {
       cout<<n<<"=";
    stack<int>s;
      while(n!=0)
      {
          int a=n%r;
         n=n/r;
         //如果余数a小于0,怎余数+(-r),此时需要借一位,则n++。
          if(a<0){a-=r,n++;}
          s.push(a);
      }
      while(!s.empty())

        {cout<<ch[s.top()];
        s.pop();
        }
      cout<<"(base"<<r<<")"<<endl;
   }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/gzr2018/p/9782074.html