CF132A Turing Tape 题解

Content

读入一个字符串 \(s\),让你用以下规则将字符串中的所有字符转换成数字:

  • 先将这个字符的 \(\texttt{ASCII}\) 码的 \(8\)\(2\) 进制数反转,再将这个数转化为十进制数,记为 \(x\)。例如 \(\texttt{H}\)\(\texttt{ASCII}\) 码是 \(72=(01001000)_2\),将其反转得 \((00010010)_2=18\)
  • 取出上一步的反转结果 \(res\)(第一步 \(res=0\)),求出最终的数字 \(a=(res-x)\mod256\)。例如,\(\texttt{H}\) 作为第一个字符出现在字符串中,那么它的最终转换的数字就是 \((0-18)\mod256=238\)

数据范围:\(1\leqslant|s|\leqslant100\),各个字符的 \(\texttt{ASCII}\) 码在 \(32\)\(126\) 之间(包含 \(32\)\(126\))。

Solution

就是一道模拟题目。

首先得出字符的 \(\texttt{ASCII}\) 码以后我们把它转换为一个 \(8\) 位二进制的数,再反转。这个可以用一个数组来保存。

我们再调出上一次的结果(可以用一个变量保存,初始值为 \(0\)),然后求出来结果。注意,如果是负数,那么先要把它给加上 \(256\),使其变为正数,然后再取模。

Code

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
using namespace std;

string s;
int pre;

int main() {
	getline(cin, s);	//考虑到可能读入空格,用getline读入字符串
	pre = 0;
	for(int i = 0; i < s.size(); ++i) {
		int x = (int)s[i], num[17] = {0}, newx = 0;
		for(int j = 7; j >= 0; --j)	if(x >= (int)pow(2, j)) num[j] = 1, x -= pow(2, j);
		for(int j = 0; j <= 7; ++j)	newx += num[j] * pow(2, 7 - j);
		printf("%d\n", (pre - newx + 256) % 256);
		pre = newx;
	}
}
posted @ 2021-12-21 21:02  Eason_AC  阅读(46)  评论(0)    收藏  举报