Check if integer has repeating digits. No string methods or arrays

前端 未结 4 748
你的背包
你的背包 2021-01-22 05:33

I\'m trying to see if an int has multiples of the same digit. Trying to do it without string methods or arrays. The main method I\'m having trouble with is hasDistinctDigi

4条回答
  •  后悔当初
    2021-01-22 05:41

    Here is a short and sweet version :)

     private static boolean hasDistinctDigits(int number) {
         int numMask = 0;
         int numDigits = (int) Math.ceil(Math.log10(number+1));
         for (int digitIdx = 0; digitIdx < numDigits; digitIdx++) {
             int curDigit = (int)(number / Math.pow(10,digitIdx)) % 10;
             int digitMask = (int)Math.pow(2, curDigit);             
             if ((numMask & digitMask) > 0) return false;
             numMask = numMask | digitMask;
         }
         return true;
     }
    

    It works in a pretty simply way. numMask is an integer used to store what digits have already been encountered (since a decimal system number has only 10 digits and an integer gives use 16-bits, we have enough bits to store each decimal digit as it occurs).

    We loop over all digits in the number. For each digit index, we get the actual digit in curDigit. Let's say the current digit is 5. We then check it the 5th bit is raised in out numMask: if it is, then we have already encounter a 5 in the past, so we can immediately tell that the number does not have all distinct digits and return false; otherwise, we modify numMask and raise the 5th bit.

    If we make it to the end, then no dupicate digits were encountered.

提交回复
热议问题