246. Strobogrammatic Number

LeetCode easy original: C# #csharp #easy #leetcode #string
El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

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

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

Ejemplo

Input: num = "69"

Output: true

C# solución

coincidente/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++ solución

borrador 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 solución

coincidente/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 solución

coincidente/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 solución

coincidente/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 solución

coincidente/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.

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.