50 lines
1.5 KiB
HTML
50 lines
1.5 KiB
HTML
<!doctype html>
|
|
<html lang="de">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<title>Übung 7: Rekursive Umkehrung eines Strings</title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
|
</head>
|
|
<body>
|
|
<main>
|
|
<div class="container py-5">
|
|
<div class="alert alert-primary">
|
|
<h2>Übung 7: Rekursive Umkehrung eines Strings</h2>
|
|
<p>Schreibe eine rekursive Funktion in JavaScript, die einen gegebenen String umkehrt.</p>
|
|
</div>
|
|
</div>
|
|
</main>
|
|
<script>
|
|
'use strict';
|
|
|
|
// const recurse = (str, nr) => {
|
|
// if (nr < 0) {
|
|
// return '';
|
|
// }
|
|
|
|
// return str.charAt(nr) + recurse(str, nr - 1);
|
|
// };
|
|
|
|
// const reverseString = (str) => {
|
|
// return recurse(str, str.length - 1);
|
|
// };
|
|
|
|
function reverseString(str) {
|
|
// Base case: if the string has only one character, return it
|
|
if (str.length <= 1) {
|
|
return str;
|
|
}
|
|
// Recursive case: return the last character of the string and call the function with the rest of the string
|
|
return reverseString(str.slice(1)) + str[0];
|
|
}
|
|
|
|
// Test cases
|
|
console.log(reverseString('hello')); // => "olleh"
|
|
console.log(reverseString('Recursion')); // => "noisruceR"
|
|
console.log(reverseString('')); // => ""
|
|
console.log(reverseString('A')); // => "A"
|
|
</script>
|
|
</body>
|
|
</html>
|