标签:blog os io for ar 2014 log amp sp
题目:进制转换,加上合法判断。
分析:数论。先转化成十进制,再转化成对应的进制,输出即可。
base进制转化成十进制:顺序乘以base加和;
十进制转base进制:逆序输出模base的余数。
说明:注意值时0的情况。
#include <iostream> #include <cstdlib> #include <cstdio> using namespace std; char number1[11]; int ctoi( char ch ) { if ( ch >= '0' && ch <= '9' ) return ch - '0'; else return ch - 'A' + 10; } char itoc( int v ) { if ( v < 10 ) return v + '0'; else return v + 'A' - 10; } void dtob2( long long v, int b2 ) { if ( v ) { dtob2( v/b2, b2 ); printf("%c",itoc(v%b2)); } } int main() { int base1,base2; while (~scanf("%d%d%s",&base1,&base2,number1)) { //非法判断 int flag = 0; for ( int i = 0 ; number1[i] ; ++ i ) if ( ctoi(number1[i]) >= base1 ) flag = 1; if ( flag ) { printf("%s is an illegal base %d number\n",number1,base1); continue; } //转化成10进制的值 long long value = 0LL; for ( int i = 0 ; number1[i] ; ++ i ) { value *= base1; value += ctoi(number1[i]); } //转化成base2进制数 printf("%s base %d = ",number1,base1); if (value == 0LL) printf("0"); else dtob2(value, base2); printf(" base %d\n",base2); } return 0; }
UVa 355 - The Bases Are Loaded
标签:blog os io for ar 2014 log amp sp
原文地址:http://blog.csdn.net/mobius_strip/article/details/38816257