华为的一道机考题,大端与小端

现定义一种字符编码,其编码格式如下:
第一个字符表示后续8个字符序(字符‘0’表示小端,字符‘1’表示大端)
后续8个字符,每个字符代表一个字节
编码解析之后字符串采用大端模式
例如编码组“012345678”,解析之后的大端字符串为“87654321”(反过来了),编码组“112345678”,解析之后的大端字符串为“12345678”
一次可以连续输入很多个编码组
很简答,代码如下

#include <iostream>
#include <string>
using namespace std;

int main()
{
	int n;
	cin >> n;
	string s;
	cin >> s;
	int is = 0;
	while (s[is] != '\0')
	{
		if (s[is] == '0')
		{
			string s_temp = s.substr(is + 1, 8);
			string s_temp_inverse(s_temp.rbegin(), s_temp.rend());
			cout<< s_temp_inverse<<" ";
			is += 9;
		}
		if (s[is] == '1')
		{
			string s_temp = s.substr(is + 1, 8);
			cout << s_temp << " ";
			is += 9;
		}
	}
	system("pause");
	return 0;
}

如果不是9位的一个组,自己可以可以找0和1的位置,编码如下

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
	int n;
	cin >> n;
	if (n < 1)
		return 0;
	string p;
	cin >> p;
	int pro = 0;
	int pos = min(p.find("0", 0), p.find("1", 0));
	while (true) {
		int pro = min(p.find("0", pos + 1), p.find("1", pos + 1));
		if (pro == p.npos) {
			if (p[pos] == '0') {
				string a = p.substr(pos + 1, p.length() - pos +1);
				cout << a;
			}
			else
			{
				for (int i = p.length() - 1; i > pos; i--) {
					cout << p[i];
				}
			}
			break;
		}
		else {
			if (p[pos] == '1') {
				for (int i = pro - 1; i > pos; i--) {
					cout << p[i];
				}
				cout << " ";
			}
			else
			{
				string a = p.substr(pos + 1, pro-pos-1);
				cout << a << " ";
			}
		}
		pos = pro;
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值