246. Strobogrammatic Number

LeetCode easy original: C# #csharp #easy #leetcode #string
Il testo del problema è tradotto dal russo per la lingua selezionata. Il codice resta invariato.

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

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

Esempio

Input: num = "69"

Output: true

C# soluzione

abbinato/originale
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++ soluzione

bozza automatica, rivedere prima dell'invio
#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 soluzione

abbinato/originale
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 soluzione

abbinato/originale
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 soluzione

abbinato/originale
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 soluzione

abbinato/originale
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

offerte attive with overlapping task tags are mostrati.

Tutte le offerte
Non ci sono ancora offerte attive.