vault backup: 2023-09-14 21:33:26

This commit is contained in:
2023-09-14 21:33:26 +02:00
parent db3377799d
commit 907869bee6
2 changed files with 46 additions and 9 deletions

View File

@ -305,3 +305,40 @@ let rec quo a b =
else
1 + quo (a-b) b ;;
```
## Exercise 4.9
```Ocaml
let rec reverse n =
let str_n = string_of_int n in
let len = String.length str_n in
let rec reverse_helper index =
if index < 0 then
""
else
String.make 1 str_n.[index] ^ reverse_helper (index - 1)
in
reverse_helper (len - 1) ;;
let rec reverse_int n =
let rec reverse_helper acc remaining =
if remaining = 0 then
acc
else
let last_digit = remaining mod 10 in
let new_acc = acc * 10 + last_digit in
let new_remaining = remaining / 10
in reverse_helper new_acc new_remaining in reverse_helper 0 n ;;
```
## Exercise 4.10
```Ocaml
let rec multiply x y =
if x = 0 || y = 0 then
0
else if x mod 2 = 0 then
multiply (x / 2) (y * 2)
else
y + multiply (x / 2) (y * 2)
```