题解:SP21169 TAP2014B - Balanced base-3

· · 题解

题目大意

将一个十进制数转换为平衡三进制数。

平衡三进制数与普通三进制数的不同在于平衡三位数是由 0 , +1 , 1 构成的。

分析

我们回想一下十进制数 n 转换为三进制数的算法:

  1. 计算 n 除以 3 的余数,并记录。
  2. 令 n = n \div 3。(只取整数部分)
  3. 重复以上步骤,直至 n = 0 为止。
  4. 倒序输出记录的数字。

对于平衡三进制数,我们可以仿照转换为普通三进制数进行操作,在第一步中分类讨论:

代码

根据以上的说法,我们可以写出代码:

#include<bits/stdc++.h>
using namespace std;
int main(){
    int T;
    cin>>T;
    while(T--){
        int n;
        cin>>n;
        if(n==0){
            cout<<"0"<<endl;
            continue;
        }
        stack<char> st;
        while(n>0){
            int now=n%3;
            n/=3;
            if(now==0)st.push('0');
            else if(now==1)st.push('+');
            else if(now==2){
                st.push('-');
                n++;  //向高位进1
            }
        }
        while(!st.empty()){
            cout<<st.top();
            st.pop();
        }
        cout<<endl;
    }

    return 0;
}

总结

这题是一道不错的进制转换题,相当于普通的进制转换,它修改了原有的机制,但是我们仍然可以运用思维将其进行转换,这就是这题的核心。