How to check if a specific digit is in an integer

前端 未结 5 1044
我在风中等你
我在风中等你 2020-12-11 21:58

I want to check if, for example, the digit \'2\' is in 4059304593. My aim is to then check if there are any of the digits 1-9 not in my integer. This is what I have tried:

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 22:36

    This "digit" thing calls for a string approach, not a numeric one (reminds me of some Project Euler puzzles).

    I'd create a set out of the digits of your number first (removing duplicates at the same time)

    s = set(str(4059304593))
    

    then to check for a digit:

    print('2' in s)
    

    (note that in for a set is performant)

    then, to check whether s contains all the 013456789 digits:

    print(s.issuperset("013456789"))
    

    (if this must be done multiple times, it may be worth to create a set with the string, issuperset will work faster)

提交回复
热议问题