246. Strobogrammatic Number

LeetCode easy original: C# #csharp #easy #leetcode #string
O texto da tarefa é traduzido do russo para o idioma selecionado. O código permanece sem alterações.

Дана string num, представляющая собой inteiro. return true, если num является стробограмматическим numberм.

Стробограмматическое number — это number, которое выглядит одинаково при повороте на 180 градусов (если посмотреть вверх ногами).

Exemplo

Input: num = "69"

Output: true

C# solução

correspondente/original
using System.Text;
public class Solution {
    public bool IsStrobogrammatic(string num) {
        StringBuilder rotated = new StringBuilder();
        for (int i = num.Length - 1; i >= 0; i--) {
            char c = num[i];
            if (c == '0' || c == '1' || c == '8') {
                rotated.Append(c);
            } else if (c == '6') {
                rotated.Append('9');
            } else if (c == '9') {
                rotated.Append('6');
            } else {
                return false;
            }
        }
        return num == rotated.ToString();
    }
}

C++ solução

rascunho automático, revisar antes de enviar
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public bool IsStrobogrammatic(string num) {
        StringBuilder rotated = new StringBuilder();
        for (int i = num.size() - 1; i >= 0; i--) {
            char c = num[i];
            if (c == '0' || c == '1' || c == '8') {
                rotated.Append(c);
            } else if (c == '6') {
                rotated.Append('9');
            } else if (c == '9') {
                rotated.Append('6');
            } else {
                return false;
            }
        }
        return num == rotated.ToString();
    }
}

Java solução

correspondente/original
class Solution {
    public boolean isStrobogrammatic(String num) {
        StringBuilder rotatedStringBuilder = new StringBuilder();
        for (int i = num.length() - 1; i >= 0; i--) {
            char c = num.charAt(i);
            if (c == '0' || c == '1' || c == '8') {
                rotatedStringBuilder.append(c);
            } else if (c == '6') {
                rotatedStringBuilder.append('9');
            } else if (c == '9') {
                rotatedStringBuilder.append('6');
            } else {
                return false;
            }
        }
        String rotatedString = rotatedStringBuilder.toString();
        return num.equals(rotatedString);
    }
}

JavaScript solução

correspondente/original
class Solution {
    isStrobogrammatic(num) {
        let rotated = "";
        for (let i = num.length - 1; i >= 0; i--) {
            const c = num[i];
            if (c === '0' || c === '1' || c === '8') {
                rotated += c;
            } else if (c === '6') {
                rotated += '9';
            } else if (c === '9') {
                rotated += '6';
            } else {
                return false;
            }
        }
        return num === rotated;
    }
}

Python solução

correspondente/original
class Solution:
    def isStrobogrammatic(self, num: str) -> bool:
        rotated = []
        for c in reversed(num):
            if c in '018':
                rotated.append(c)
            elif c == '6':
                rotated.append('9')
            elif c == '9':
                rotated.append('6')
            else:
                return False
        return num == ''.join(rotated)

Go solução

correspondente/original
func isStrobogrammatic(num string) bool {
    rotated := ""
    for i := len(num) - 1; i >= 0; i-- {
        switch num[i] {
        case '0', '1', '8':
            rotated += string(num[i])
        case '6':
            rotated += "9"
        case '9':
            rotated += "6"
        default:
            return false
        }
    }
    return num == rotated
}

Algorithm

1️⃣

Создайте новую строку, перебирая оригинальную строку num в обратном порядке. Для каждого символа проверьте, является ли он допустимым для поворота (0, 1, 6, 8, 9). Если символ недопустим (2, 3, 4, 5, 7), немедленно return false.

2️⃣

Для каждого допустимого символа добавьте его соответствующее значение после поворота (0 ⟶ 0, 1 ⟶ 1, 6 ⟶ 9, 8 ⟶ 8, 9 ⟶ 6) в новую строку.

3️⃣

Сравните полученную строку с исходной строкой num. Если они равны, return true, в противном случае return false.

😎

Vacancies for this task

vagas ativas with overlapping task tags are mostradas.

Todas as vagas
Ainda não há vagas ativas.