ZOJ 3713 In 7-bit (题意不好理解,十进制、二进制、十六进制的转换问题)
考验理解能力的时候到了 T^T
Very often, especially in programming contests, we treat a sequence of non-whitespace
characters as a string. But sometimes, a string may contain whitespace characters or
even be empty. We can have such strings quoted and escaped to handle these cases.
However, a different approach is putting the length of the string before it.
As most strings are short in practice, it would be a waste of space to encode
the length as a 64-bit unsigned integer or add a extra separator between the
length and the string. That's why a 7-bit encoded integer is introduced here. To store the string length by 7-bit encoding, we should regard the length as
a binary integer. It should be written out by seven bits at a time, starting
with the seven least-significant (i.e. 7 rightmost) bits. The highest
(i.e. leftmost) bit of a byte indicates whether there are more bytes to be
written after this one. If the integer fits in seven bits, it takes only
one byte of space. If the integer does not fit in seven bits, the highest
bit is set to 1 on the first byte and written out. The integer is then
shifted by seven bits and the next byte is written. This process is
repeated until the entire integer has been written. With the help of 7-bit encoded integer, we can store each string as a
length-prefixed string by concatenating its 7-bit encoded length and its raw content (i.e. the original string).
题目大意:
给定一个字符串,按照十六进制输出,但是对于字符串的长度的输出比较麻烦。
首先是将长度len转换成二进制,取后七位,如果除去后七位前边还有1那么就在第八位位置加上1,
然后将len右移7位,继续上述步骤,
例如10001000100,那么第一次取出来的后七位就是1000100,因为前边还有1,
所以第一次取出来的变为11000100,然后将len右移7位得到1000,依次输出他们的十六进制就可以了
对于一个十进制的数先转换成二进制取后七位,再转换成十进制,就相当于十进制的数取后128位,也就是 len%128
Source Code:
#include <bits/stdc++.h> using namespace std; string str; int main () { int i, j, t, n, m, k, u, v; cin >> t; getchar (); while (t--) { getline (cin, str); int len = str.size (); if (0 == len) { printf ("00\n"); continue; } int l = len; while (l) { int tmp = l % 128; l /= 128; if (l) { tmp += 128; } printf ("%02X", tmp); } for (i = 0; i < len; ++i) { printf ("%02X", str[i]); } printf ("\n"); } return 0; }