题解 | #字符串分隔#
字符串分隔
https://www.nowcoder.com/practice/d9162298cb5a437aad722fccccaae8a7
解题思路
- 读取输入字符串
- 判断字符串长度,如果不是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();
// 补充0直到长度是8的倍数
StringBuilder sb = new StringBuilder(str);
int remainder = sb.length() % 8;
if (remainder != 0) {
for (int i = 0; i < 8 - remainder; i++) {
sb.append('0');
}
}
// 每8个字符输出一行
for (int i = 0; i < sb.length(); i += 8) {
System.out.println(sb.substring(i, i + 8));
}
}
}
s = input()
# 补充0使长度为8的倍数
remainder = len(s) % 8
if remainder != 0:
s += '0' * (8 - remainder)
# 每8个字符分割并输出
for i in range(0, len(s), 8):
print(s[i:i+8])
算法及复杂度
- 算法:字符串处理,按固定长度分割
- 时间复杂度:
- 其中n为输入字符串的长度
- 空间复杂度:
- 需要存储处理后的字符串