簡體   English   中英

給定一個非負的 integer N,返回類似於 Python 中 N 的非負整數的個數

[英]Given a non-negative integer N, returns the number of non-negative integers similar to N in Python

開發一個function:

如果兩個非負整數 N 和 M 的十進制表示可以通過重新排列它們的數字彼此獲得,則稱它們是相似的。 請注意,正確的十進制表示不包含前導零。

Class solution { public int solution(int N); }

即,給定一個非負 integer N,返回類似於 N 的非負整數的數量。

例如,給定 N =1213,function 應該返回 12,因為有 12 個整數類似於 1213,即:1123、1132、1213、1231、1312、1321、2113、2131、23111、31211、3

給定 N = 123,function 應該返回 6,因為有六個類似於 123 的整數,即:123、132、213、231、312 和 321

給定 N = 100,function 應該返回 1,因為只有一個類似的 integer。 001 和 010 都是不正確的整數十進制表示。

鑒於 N = 0,function 應該返回 1,因為只有一個類似的 integer(數字本身)。

目前,我有一個 function 可以創建所有排列,盡管 N = 1213 我有超過 12 個排列。我不知道他們是如何得到這個數字的。

def solution(N):
  
   res = [int(x) for x in str(N)] 
   result_perms = [[]]
   
   for n in res:
       new_perms = []
       for perm in result_perms:
         for i in range(len(perm)+1):
           new_perms.append(perm[:i] + [n] + perm[i:])
           result_perms = new_perms
   return result_perms
   

itertools對這類問題很有用。 我的解決方案:

import itertools
def solution(N):
    count = 0
    for i in set(itertools.permutations(str(N))): # we use set() to eliminate duplicates, and cast N to a string to make it iterable
        perm = "".join(i)
        if str(int(perm))==perm and int(perm) >= 0: #check to ensure that we have no 0's at the front of this permutation
            count += 1
    return count

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM