Extraction de la plus longue chaîne numérique
Le problème consiste à extraire la plus longue sous-chaîne numérique d'une chaîne donnée. Si plusieurs sous-chaînes numériques ont la même longueur, on retourne celle qui apparaît en dernier.
import java.util.*;
public class ExtractionChaineNumerique {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.nextLine();
String cleanedInput = input.replaceAll("[a-zA-Z]", " ");
String[] parts = cleanedInput.split(" ");
Map<Integer, String> map = new LinkedHashMap<>();
for (String part : parts) {
if (!part.isEmpty() && !part.startsWith(" ")) {
map.put(part.length(), part);
}
}
int maxLength = 0;
String longestNumber = "";
for (Map.Entry<Integer, String> entry : map.entrySet()) {
if (entry.getKey() >= maxLength) {
maxLength = entry.getKey();
longestNumber = entry.getValue();
}
}
System.out.println(longestNumber + "," + maxLength);
}
sc.close();
}
}
Analyse d'un tableau d'octets
Le problème consiste à analyser un tableau d'octets pour extraier des valeurs numériques basées sur des positions spécifiées en bits. Les entrées comprennent la longueur du tableau, le tableau lui-même, le nombre de valeurs à extraire, et les positions de bits pour chaque valeur.
import java.util.Scanner;
public class AnalyseTableauOctets {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int length = sc.nextInt();
String[] bytes = new String[length];
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < length; i++) {
bytes[i] = sc.next();
hexString.append(bytes[i]);
}
int numElements = sc.nextInt();
int[] bitPositions = new int[numElements];
for (int i = 0; i < numElements; i++) {
bitPositions[i] = sc.nextInt();
}
String binaryString = hexString.toString().replaceAll("0x", "");
StringBuilder binaryConcat = new StringBuilder();
for (String hex : binaryString.split(" ")) {
if (!hex.isEmpty()) {
binaryConcat.append(hexToBinary(hex));
}
}
int start = 0;
for (int i = 0; i < numElements; i++) {
String binaryValue = binaryConcat.substring(start, start + bitPositions[i]);
System.out.println(Integer.parseInt(binaryValue, 2));
start += bitPositions[i];
if (i + 1 < numElements) {
start += bitPositions[i + 1];
}
}
}
sc.close();
}
private static String hexToBinary(String hex) {
if (hex == null || hex.length() % 2 != 0) {
return null;
}
StringBuilder binary = new StringBuilder();
for (int i = 0; i < hex.length(); i++) {
String bin = Integer.toBinaryString(Integer.parseInt(hex.substring(i, i + 1), 16));
while (bin.length() < 4) {
bin = "0" + bin;
}
binary.append(bin);
}
return binary.toString();
}
}