Checking whether two numbers are permutation of each other?

前端 未结 7 2035
借酒劲吻你
借酒劲吻你 2021-02-15 22:44

Given two numbers a, b such that 1 <= a , b <= 10000000000 (10^10). My problem is to check whether the digits in them are permutation of each other or not. What is the fas

7条回答
  •  心在旅途
    2021-02-15 23:46

    If what i understood from your question correctly a permutation is a combination of the elements, which do not repeat. So if 123 is a valid permutation of 312 then so does

    123,
    213,
    132,
    321,
    213, 
    

    and so on.

    So based on this assumption lets say you got two integers 123456789 and 129837456. (For simplicity i am also assuming that both numbers have equal length). If you understood the point then you might be able to check for different permutations and combination as well.

    for that all you need to do is to get the integers of units out of the given number, e.g:

    Number 123456789 is
    1 * 100000000 + 
    2 * 10000000  +
    3 * 1000000   +
    4 * 100000    +
    5 * 10000     +
    6 * 1000      +
    7 * 100       +
    8 * 10        +
    9 
    

    or

    1 * power(10, 8) +
    2 * power(10, 7) +
    3 * power(10, 6) +
    4 * power(10, 5) +
    5 * power(10, 4) +
    6 * power(10, 3) +
    7 * power(10, 2) +
    8 * power(10, 1) +
    9 * power(10, 0) 
    

    i have literally given you algorithmic hint of how to do that so this can easily be done. once done you will end up with separate integers (better save these values in an array)

    1, 2, 3, 4, 5, 6, 7, 8, 9
    

    Now

    do the same for the other given integer so you will end up with another array of integers

    1, 2, 9, 8, 3, 7, 4, 5, 6
    

    so now all you need to check is that if all of the integers of the second array are present in the first array of integers, if yes then they are a permutation of the integers of the first array or the first number.

    I hope this helps.

提交回复
热议问题