华为OD机试 - 数据单元的变化替换(Java & JS & Python & C & C++)
以下是不同编程语言的解决方案:
Java:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] parts = input.split(",");
for (int i = 0; i < parts.length; i++) {
if (parts[i].equals("-1")) {
parts[i] = String.valueOf(i);
}
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
result.append(parts[i]);
if (i < parts.length - 1) {
result.append(",");
}
}
System.out.println(result.toString());
sc.close();
}
}
JavaScript:
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
var parts = chunk.trim().split(',');
for (var i = 0; i < parts.length; i++) {
if (parts[i] === '-1') {
parts[i] = i.toString();
}
}
console.log(parts.join(','));
});
Python:
input_str = input()
elements = input_str.split(',')
for i, elem in enumerate(elements):
if elem == '-1':
elements[i] = str(i)
print(','.join(elements))
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replace_minus_one(char *input, int length) {
char *token;
int i = 0;
token = strtok(input, ",");
while (token != NULL) {
if (strcmp(token, "-1") == 0) {
sprintf(token, "%d", i);
}
token = strtok(NULL, ",");
i++;
}
}
int main() {
char input[1000];
gets(input); // 注意:请不要在实际代码中使用 `gets`, 因为它不安全
replace_minus_one(input, strlen(input));
printf("%s\n", input);
return 0;
}
C++:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
std::string token;
int i = 0;
whi
评论已关闭