1056. Confusing Number

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

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

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

Ejemplo:

Input: n = 6

Output: true

C# solución

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

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

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

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

coincidente/original
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 градусов.

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

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

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.