Платформа: CodeWars
Название задачи: Simple Fun #384: Is Turing's Equation? (Простое развлечение)
Ссылка на задачу: https://www.codewars.com/kata/5a1e6323ffe75f71ae000026
Сложность: 7 kyu
Уже решили (На момент написания статьи): 1 946 из 6 491
Тэги: Основы, строки, математика
Оригинальное описание задачи:
Story
Joe Stoy, in his book "Denotational Semantics", tells following story:
The decision which way round the digits run is, of course, mathematically trivial. Indeed, one early British computer had numbers running from right to left (because the spot on an oscilloscope tube runs from left to right, but in serial logic the least significant digits are dealt with first).
Turing used to mystify audiences at public lectures when, quite by accident, he would slip into this mode even for decimal arithmetic, and write things like 73+42=16.
The next version of the machine was made more conventional simply by crossing the x-deflection wires: this, however, worried the engineers, whose waveforms were all backwards. That problem was in turn solved by providing a little window so that the engineers (who tended to be behind the computer anyway) could view the oscilloscope screen from the back.
[C. Strachey - private communication.]
You will play the role of the audience and judge on the truth value of Turing's equations.
Task
You are given a string `s`. It's an equation such as "a+b=c", where `a`, `b`, `c` are numbers made up of digits 0 to 9. This includes possible leading or trailing zeros. The equations will not contain any spaces.
Your task is to determine whether `s` is a valid Turing equation. Return `true` or `false`, respectively, in Turing's interpretation, i.e. the numbers being read backwards.
Examples
For `s = "73+42=16"`, the output should be `true`:
73 -> 37
42 -> 24
16 -> 61
37+24==61
For `s = "5+8=13"`, the output should be `false`:
5 -> 5
8 -> 8
13 -> 31
5+8!=31
For `s = "10+20=30"`, the output should be `true`:
10 -> 01 -> 1
20 -> 02 -> 2
30 -> 03 -> 3
1+2==3
Note:
- All the numbers `a`, `b`, `c` have no more than 10 digits, excluding leading zeros (read backwards).
- `s` contains only digits, `+`, and `=`. Characters like `-`, `*`, or `/` will not appear in the string.
Пояснение задачи:
Задача заключается в проверке корректности арифметического выражения, записанного в необычной форме, где числа представлены задом наперёд (от младшего значащего разряда к старшему).
Нам дано выражение вида "a+b=c", где `a`, `b`, `c` — это десятичные числа, состоящие из цифр от 0 до 9, записанные в обратном порядке.
Основные шаги решения:
1. Разделим строку на три части: левую часть (`a`), правую часть (`b`) и итоговое число (`c`).
2. Преобразуем каждую часть выражения в обратную форму (перевернём цифры числа):
- Например, число `123` превращается в `321`.
3. Переведём перевернутые числа обратно в десятичную систему счисления.
4. Проверим равенство суммы левой и правой частей выражению, представленному в обратной записи.
Примеры:
- Для строки "73+42=16": - Число `73` переворачивается в `37`, число `42` — в `24`, итоговое число `16` — в `61`.
-Проверяем: 37 + 24 = 61 — верно.
- Для строки "5+8=13": - Число `5` остаётся `5`, число `8` остаётся `8`, итоговое число `13` переворачивается в `31`.
- Проверяем: 5 + 8 ≠ 31 — неверно.
- Для строки "10+20=30": - Число `10` переворачивается в `01`, число `20` — в `02`, итоговое число `30` — в `03`.
- Проверяем: 01 + 02 = 03 — верно.
Таким образом, задача сводится к переворачиванию чисел, представлению их в обычной десятичной системе и проверке арифметического равенства.