1056. Confusing Number

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

Запутанное number - это number, которое при повороте на 180 градусов становится другим numberм, каждая цифра которого действительна. Мы можем повернуть цифры числа на 180 градусов, чтобы получить новые цифры. Когда 0, 1, 6, 8 и 9 поворачиваются на 180 градусов, они становятся 0, 1, 9, 8 и 6 соответственно.

При повороте на 180 градусов 2, 3, 4, 5 и 7 становятся недействительными. Обратите внимание, что после поворота числа мы можем игнорировать ведущие нули. НаEsempio, после поворота 8000 мы получим 0008, которое считается просто 8. Если заgiven intero n, return true, если это запутанное number, или false в противном случае.

Esempio:

Input: n = 6

Output: true

C# soluzione

abbinato/originale
public class Solution {
    public bool IsConfusingNumber(int n) {
        string nStr = n.ToString();
        Dictionary<char, char> rotationMap = new Dictionary<char, char> {
            {'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}
        };
        StringBuilder rotatedStr = new StringBuilder();
        foreach (char ch in nStr) {
            if (!rotationMap.ContainsKey(ch)) {
                return false;
            }
            rotatedStr.Insert(0, rotationMap[ch]);
        }
        return rotatedStr.ToString() != nStr;
    }
}

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 IsConfusingNumber(int n) {
        string nStr = n.ToString();
        unordered_map<char, char> rotationMap = new unordered_map<char, char> {
            {'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}
        };
        StringBuilder rotatedStr = new StringBuilder();
        foreach (char ch in nStr) {
            if (!rotationMap.count(ch)) {
                return false;
            }
            rotatedStr.Insert(0, rotationMap[ch]);
        }
        return rotatedStr.ToString() != nStr;
    }
}

Java soluzione

abbinato/originale
public class Solution {
    public boolean isConfusingNumber(int n) {
        String nStr = String.valueOf(n);
        StringBuilder rotatedStr = new StringBuilder();
        Map<Character, Character> rotationMap = Map.of(
            '0', '0', '1', '1', '6', '9', '8', '8', '9', '6'
        );

        for (char ch : nStr.toCharArray()) {
            if (!rotationMap.containsKey(ch)) {
                return false;
            }
            rotatedStr.insert(0, rotationMap.get(ch));
        }

        return !nStr.equals(rotatedStr.toString());
    }
}

JavaScript soluzione

abbinato/originale
function isConfusingNumber(n) {
    const rotationMap = {
        '0': '0', '1': '1', '6': '9', '8': '8', '9': '6'
    };
    const nStr = n.toString();
    let rotatedStr = "";

    for (let char of nStr) {
        if (!(char in rotationMap)) {
            return false;
        }
        rotatedStr = rotationMap[char] + rotatedStr;
    }

    return rotatedStr !== nStr;
}

Python soluzione

abbinato/originale
def isConfusingNumber(n):
    rotation_map = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
    n_str = str(n)
    rotated_str = ""

    for char in n_str:
        if char not in rotation_map:
            return False
        rotated_str = rotation_map[char] + rotated_str

    return rotated_str != n_str

Go soluzione

abbinato/originale
package main

import (
    "strconv"
)

func isConfusingNumber(n int) bool {
    rotationMap := map[rune]rune{'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
    nStr := strconv.Itoa(n)
    rotatedStr := ""

    for _, ch := range nStr {
        if _, exists := rotationMap[ch]; !exists {
            return false
        }
        rotatedStr = string(rotationMap[ch]) + rotatedStr
    }

    return rotatedStr != nStr
}

Algorithm

Преобразуй number в строку для удобства работы с его цифрами.

Используй словарь для хранения соответствий цифр при повороте на 180 градусов.

Пройди по цифрам числа, проверяя, что все цифры действительны и заменяя их на соответствующие при повороте.

Проверь, что перевернутая stringa отличается от исходной.

😎

Vacancies for this task

offerte attive with overlapping task tags are mostrati.

Tutte le offerte
Non ci sono ancora offerte attive.