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

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

Output

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 the left.

Sample Input
15 43 71
Sample Output
#123456

这个题目的本质是考察除k取余法,方法为用十进制数去除以基数k,每次把商数作为下一次的值,余数写在旁边,一直做到商数小于基数,结束运算,然后从下到上,从最后一个商数到第一个余数的路径上所有的数构成了结果,例如将十进制数38转化为13进制数(0-9,A-C)

从下到上,分别是2、12,这个数是2C,故38的13进制形式为2C,按照这个方法设计程序即可。

因为13进制涉及到了字母,因此使用string来存储这个数字,每次在string头部插入字符。

#include <iostream>
#include <vector>
#include <string>
#include <string.h>

using namespace std;

char int2char(int n){
    if(n <= 9){
        return '0' + n;
    }else{
        return 'A' + (n - 10);
    }
}

string convertMars(int value){
    string temp;
    int shang,yu;
    int radix = 13;
    while(1){
        shang = value / radix;
        yu = value % radix;
        temp.insert(temp.begin(),int2char(yu));
        value /= radix;
        if(value < radix){
            temp.insert(temp.begin(),int2char(value));
            break;
        }
    }
    return temp;
}

int main()
{
    string mR,mG,mB;
    int R,G,B;
    cin >> R >> G >> B;
    mR = convertMars(R);
    mG = convertMars(G);
    mB = convertMars(B);
    cout << "#" << mR << mG << mB;
    return 0;
}



posted on 2015-06-05 15:42  张大大123  阅读(120)  评论(0编辑  收藏  举报

导航