School-HTML/3AIN/Esercizi TPS JavaScript Misti/esercizio2.html

41 lines
1.5 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>Verifica Bit di parità</title>
</head>
<body>
<h1>Verifica Bit di parità</h1>
<input type="number" id="numero">
<br>
<button onclick="calcola();">Calcola</button>
<hr>
<h1>Risultato</h1>
<p id="risultato">...</p>
<script>
function calcola() {
let numero = document.getElementById("numero").value;
let contatore_uni = 0;
for (let i = 0; i < numero.length; i++) {
if (numero[i] == 1) {
contatore_uni++;
}
}
// SOLUZIONE SEMPLICE
if (contatore_uni == 1 || contatore_uni == 3 || contatore_uni == 5 || contatore_uni == 7) {
document.getElementById("risultato").innerHTML = "Bit di parità: 1";
} else {
document.getElementById("risultato").innerHTML = "Bit di parità: 0";
}
// SOLUZIONE PIÙ CORRETTA
let resto = contatore_uni % 2;
if (resto == 1) {
// dispari
document.getElementById("risultato").innerHTML = "Bit di parità: 1";
} else {
// pari
document.getElementById("risultato").innerHTML = "Bit di parità: 0";
}
}
</script>
</body>
</html>