PAT1027 Colors in Mars

1027 Colors in Mars (20分)
People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red, the middle 2 digits for Green, and the last 2 digits for Blue. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values.

Input Specification:
Each input file contains one test case which occupies a line containing the three decimal color values.

Output Specification:
For each test case you should output the Mars RGB value in the following format: first output #, then followed by a 6-digit number where all the English characters must be upper-cased. If a single color is only 1-digit long, you must print a 0 to its left.

Sample Input:
15 43 71
Sample Output:
#123456
/*
    题意:给三个十进制数字 分别转换成 13进制的数
*/


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

int main(){
    int k;
    stack<int> s;
    cout << '#';
    
    while(cin >> k){
        if(k == 0) cout << "00"; //特判 当输入的十进制数为 0 时
        
        while(k){ //将k的十三进制数 压入栈底
            s.push(k % 13);
            k /= 13;
        }
        
        if(s.size() == 1){ //当栈中只有一个元素
                if(s.top() == 10) cout << "0A";
            	else if(s.top() == 11) cout << "0B";
            	else if(s.top() == 12) cout << "0C";
                else cout << 0 << s.top();
                s.pop(); //出栈
        }
        else{
            while(!s.empty()){ //栈为空时 跳出循环
            	if(s.top() == 10) cout << 'A';
            	else if(s.top() == 11) cout << 'B';
            	else if(s.top() == 12) cout << 'C';
                else cout << s.top();
                s.pop();
            }
        }
    }
    
    return 0;
}

更加简洁的代码:
由于题目的数据范围为[0,168],因此给定的整数x在十三进制下一定可以表示成 x = a * 13^1 + b * 13^0
(因为168 < 13^2),于是只要想出办法求出a跟b即可.
事实上,对上面的等式两边同时整除13,可以得到[x / 13 = a];对上面的等式两边同时对13取模,可以得到
x % 13 = b; 这样就得到了 a 与 b,接下来只需输出ab即可。但是题目要求十三进制下的 10 11 12分别用
A B C代替,因此不妨开一个char型数组radix[13]来表示这种关系,即radix[0] = '0', radix[1] = '1',
..., radix[9] = '9', radix[10] = 'A', radix[11] = 'B', radix[12] = 'C';


#include <cstdio>
//建立0~13 与 '0' ~ '9', 'A' 'B' 'C' 的关系
char radix[13] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C'};

int main(){
    int r, g, b;
    scanf("%d%d%d", &r, &g, &b);
    printf("#");
    
    //输出radix[a] 与 radix[b]
    printf("%c%c", radix[r / 13], radix[r % 13]);
    printf("%c%c", radix[g / 13], radix[g % 13]);
    printf("%c%c", radix[b / 13], radix[b % 13]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值