Binärzahl inkrementieren (Rekursion)
Schreiben Sie eine rekursive Funktion, die als Eingabeparameter einen String aus Nullen und Einsen entgegennimmt, also eine Binärzahl, und diese um Eins inkrementiert.
z.B.
- "0" --> "1"
- "1" --> "10"
- "10" --> "11"
- "11" --> "100"
3 Kommentare
6 Lösung(en)
package ch.programmieraufgaben.rekursion.incbinary;
public class BinaerRekursivErhoehen {
public static void main(String[] args) {
new BinaerRekursivErhoehen().top();
}
void top() {
teste( "0", "1");
teste( "1", "10");
teste( "10", "11");
teste( "11", "100");
teste("100", "101");
}
void teste(String zahl, String soll) {
String ist = inkRekursiv(zahl);
System.out.print("Test " + zahl + " > " + soll);
if(ist .equals (soll)) {
System.out.println(" OK");
} else {
System.out.println(" FEHLER!! ist: " + ist + ", soll: " + soll);
}
}
String inkRekursiv(String zahl) {
// Abbruch:
if(0 == zahl.length()) {
return "1";
}
// Aufteilen in "linken Teil" und "rechteste Ziffer"
int splitPosition = zahl.length() - 1;
String linkerTeil = zahl.substring(0, splitPosition);
String rechtesteZiffer = zahl.substring( splitPosition);
if("1".equals(rechtesteZiffer)) {
return inkRekursiv(linkerTeil) + "0";
} else /* endet auf "0" */ {
return linkerTeil + "1";
}
}
} // end of class BinaerRekursivErhoehen
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
package incrementbinary;
import java.util.Scanner;
public class IncrementBinary
{
public static void main(String[] args)
{
Scanner ioScanner = new Scanner(System.in); //Scanner für manuelle Eingabe
String binaerInput = ioScanner.next();
String binaerInputInkrement = Integer.toBinaryString(Integer.parseInt(binaerInput,10)+1); //die eingegebene Binärzahl als Dezimalzahl parsen und um 1 erhöhen und die resultierende Zahl als Binärzahl wieder ausgeben
System.out.println("Input Number:" + binaerInput);
System.out.println("Increment Number:" + binaerInputInkrement);
}
}
Lösung von: Tim Otlik (Leica Camera AG)
// Autor: Andy Großhennig
// Solution for task: Binärzahl inkrementieren (Rekursion)
#include <iostream>
#include <string>
using namespace std;
void binary()
{
string sStart; //Input String
string sAdd = "1"; //String extension if all bits are '1'
string::iterator s_iStart; //Iterator for String
cout << "Binaere Zahl eingeben: ";
cin >> sStart;
cout << "\n\n";
s_iStart = (sStart.end() - 1); //Set the iterator to the last character (Not last index!!!)
// If: Analyze the binary code
if(*s_iStart == '0') //If the last character is '0', set it to '1'
*s_iStart = '1';
else if(*s_iStart == '1' && s_iStart == sStart.begin()) //If the last character '1', set it to '0' and push a '1' to the front
sStart = "10";
else
{
do //Go through the string until the index is '0'
--s_iStart;
while(*s_iStart == '1' && s_iStart != sStart.begin());
// If: Extend the string with a '1' at the front if the iterator has reached the begin of the string
if(s_iStart == sStart.begin() && *s_iStart == '1')
{
sAdd += sStart;
sStart = sAdd;
}
// Loop: Set all following Bits to '0'
while(s_iStart != (sStart.end() - 1))
{
s_iStart++;
*s_iStart = '0';
}
}
cout << sStart;
}
int main()
{
binary();
cout << "\n\n";
system("Pause");
return 0;
}
Lösung von: Andy Großhennig (Bundeswehr)
#!/usr/bin/python
# -*- coding: utf8 -*-
# Autor: Martin Schimmels
x = bin(input('Dezimalzahl eingeben: '))
print 'Eingabe = ', x, 'Nachfolger = ', bin(int(x, 2) + 1)
Lösung von: Martin Schimmels (Wilhelm-Schickard-Schule Tübingen)
// Ich persönlich würde so etwas bevorzugen...
function incrementBinary(bin) {
bin = parseInt(bin, 2) + 1;
return bin.toString(2);
}
// ... aber muss ja rekursiv sein:
function incrementBinaryRecursive(bin) {
if (typeof bin == "string") {
bin = parseInt(bin, 2);
incrementBinaryRecursive(bin++);
}
return bin.toString(2);
}
console.log(incrementBinaryRecursive("0"));
console.log(incrementBinaryRecursive("1"));
console.log(incrementBinaryRecursive("10"));
console.log(incrementBinaryRecursive("11")); // lissalanda@gmx.at
Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)
// NET 6.x | C# 10.x | VS-2022
// Aufgrund des nur einen vorliegenden Operationsschrittes habe ich auf die Rekursion verzichtet.
// Inkrement und Dekrement lassen sich hier (v) anpassen.
static string IncrementBinaryByValue(string s, int v) => Convert.ToString((int.TryParse(s, out var _) ? Convert.ToInt32(s, 2) : 0) + v, 2);
new List<string> { "0", "1", "10", "11" }.ForEach(x => Console.WriteLine($"{x} --> {IncrementBinaryByValue(x, 1)}"));
// 0-- > 1
// 1-- > 10
// 10-- > 11
// 11-- > 100
Lösung von: Jens Kelm (@JKooP)
Aktionen
Neue Lösung hinzufügen
Bewertung
Durchschnittliche Bewertung:
Kommentare (3)
Mein Algorithmus teilt weder den Binärcode, noch benutzt er Dezimalzahlen oder andere Umrechnungen.
Ich gehe den Binärcode von rechts nach links durch: Ist ganz rechts eine Null, wird sie zur Eins. Ist dort eine Eins wird soweit Stück für Stück nach Links geschaut bis eine Null auftaucht. Diese wird dann zur Eins und alle Stellen Rechts davon werden zur Null. Sind Alle Stellen Eins wird eine Eins vorne dran gehangen und alle Stellen dahinter zur Null