1056. Confusing Number

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

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

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

Exemple:

Input: n = 6

Output: true

C# solution

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

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

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

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

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

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

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

😎

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.