246. Strobogrammatic Number

LeetCode easy original: C# #csharp #easy #leetcode #string
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

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

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

Exemple

Input: num = "69"

Output: true

C# solution

correspondant/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++ solution

brouillon automatique, à relire avant soumission
#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 solution

correspondant/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 solution

correspondant/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 solution

correspondant/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 solution

correspondant/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

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.