16进制的简单运算
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
1
-
描述
-
现在给你一个16进制的加减法的表达式,要求用8进制输出表达式的结果。
-
输入
-
第一行输入一个正整数T(0<T<100000)
接下来有T行,每行输入一个字符串s(长度小于15)字符串中有两个数和一个加号或者一个减号,且表达式合法并且所有运算的数都小于31位
输出
- 每个表达式输出占一行,输出表达式8进制的结果。 样例输入
-
3 29+4823 18be+6784 4ae1-3d6c
样例输出
-
44114 100102 6565
来源
- [路过这]原创 上传者
问题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=244
问题分析:
先将16进制的数转换为10进制,然后进行加减计算,然后再将计算出的10进制结果转换为10进制进行输出。
16进制转换10进制即按权重进行累加。10进制转换8进制则为取余和除法。
代码:
优秀代码:#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <vector> #include <queue> #include <stack> #include <map> #include <string> #include <algorithm> #include <iomanip> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ struct scale16 { long long cost; void init(char *input, int start, int end) { //先将16进制的字符串转换为10进制的cost cost = 0; int c = 1; //权重 for (int i = end; i >= start; i--) { int tmp; if (input[i] >= '0' && input[i] <= '9') { tmp = input[i] - '0'; } else { tmp = input[i] - 'a' + 10; } cost += tmp*c; c *= 16; } } long long operator + (const scale16 & b)const { return cost + b.cost; } long long operator - (const scale16 & b)const { return cost - b.cost; } }; int main(int argc, char** argv) { /*freopen("file/input.txt","r",stdin); freopen("file/output.txt","w",stdout);*/ int t; scanf("%d", &t); while (t--) { char input[32]; scanf("%s", input); int length = strlen(input); int op; for (int i = 0; i <= length; i++) { if (input[i] == '+' || input[i] == '-') { op = i; break; } } scale16 a, b; a.init(input, 0, op - 1); b.init(input, op + 1, length - 1); long long ans; if (input[op] == '+') { ans = a + b; } else { ans = a - b; } int output[100]; int size = 0; //cout << ans << endl; while (ans != 0) { output[size++] = ans % 8; //cout << ans % 8 << endl; ans /= 8; } for (int i = size-1; i >= 0; i--) { printf("%d", output[i]); //cout << [i]; } printf("\n"); // cout<<a.cost<<"+"<<b.cost<<":"<<a+b<<endl; // cout<<a.cost<<"-"<<b.cost<<":"<<a-b<<endl; } //getchar(); getchar(); getchar(); return 0; }
01.
#include<stdio.h>
02.
int
main()
03.
{
04.
int
T;
05.
scanf
(
"%d"
,&T);
06.
while
(T--)
07.
{
08.
int
a,b,d;
09.
char
c;
10.
scanf
(
"%x%c%x"
,&a,&c,&b);
11.
if
(c==
'+'
) d=a+b;
12.
else
d=a-b;
13.
if
(d>=0)
14.
printf
(
"%o\n"
,d);
15.
else
printf
(
"-%o\n"
,-d);
16.
}
17.
}
分析:以%x读入16进制,以%o输出8进制。表示呵呵哒。完全不用自己处理进制的问题!
-
第一行输入一个正整数T(0<T<100000)