Checking whether two numbers are permutation of each other?

前端 未结 7 2039
借酒劲吻你
借酒劲吻你 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:31

    I've found this rather efficient solution on rossetacode.org. I hope you'll forgive me for writing it in Java (I'm not comfortable with C) but the syntax should be more or less the same.

    The code first checks to see if the numbers have the same number of digits, then sums up the digits by bit shifting them into a total. Except the shift distance is multiplied by a factor 6. This makes it impossible for smaller digits to compose the same value as a larger digit. For instance one '9' would require 64 times '8' to match its value, which obviously isn't possible.

    This code assumes non-negative input.

    boolean haveSameDigits(long n1, long n2) {
        long nn1 = n1, nn2 = n2;
        while (nn1 > 0 && nn2 > 0) {
            nn1 /= 10;
            nn2 /= 10;
        }
        if (nn2 != nn1) // not the same length
            return false;
    
        long total1 = 0, total2 = 0;
        while (n1 != 0) {
            total1 += 1L << ((n1 % 10) * 6);
            total2 += 1L << ((n2 % 10) * 6);
            n1 /= 10;
            n2 /= 10;
        }
        return total1 == total2;
    }
    

提交回复
热议问题