题目
题目链接
解题思路
- 读取输入字符串
- 判断字符串长度,如果不是8的倍数,需要在末尾补0
- 每8个字符进行分割并输出
- 具体步骤:
- 如果字符串长度不足8位,在后面补0至8位
- 如果字符串长度超过8位,按8位分割,最后不足8位的部分补0至8位
- 按顺序输出每个8位的子串
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str);
// 计算需要补充的0的个数
int remainder = str.length() % 8;
int padding = remainder == 0 ? 0 : 8 - remainder;
// 补充0
str.append(padding, '0');
// 按8个字符分割并输出
for(int i = 0; i < str.length(); i += 8) {
cout << str.substr(i, 8) << endl;
}
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
StringBuilder sb = new StringBuilder(str);
int remainder = sb.length() % 8;
if (remainder != 0) {
for (int i = 0; i < 8 - remainder; i++) {
sb.append('0');
}
}
for (int i = 0; i < sb.length(); i += 8) {
System.out.println(sb.substring(i, i + 8));
}
}
}
s = input()
remainder = len(s) % 8
if remainder != 0:
s += '0' * (8 - remainder)
for i in range(0, len(s), 8):
print(s[i:i+8])
算法及复杂度
- 算法:字符串处理,按固定长度分割
- 时间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n) - 其中n为输入字符串的长度
- 空间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n) - 需要存储处理后的字符串