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

前端 未结 4 751
你的背包
你的背包 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 06:05

    Same logic to verify if a string has unique characters can be used here. (1 << currentChar) , it sets the bit to 1 in currentChar equals to a number(0-9) present at that index and all other bits are set to 0.

    (result &(1 << currentChar) : If bit is already set to 1 then return false else

    result = result|(1 << currentChar): Set the bit in result integer which is equal to the number at that index.

    public class CheckIfDigitsAreRepeated {
    
    
            public static void main(String[] args) {
                int input = 1234567897; // false
                // int input = 1234567890;  true
    
                System.out.println(hasDistinctDigits(input));
            }
    
            public static boolean hasDistinctDigits(int input){
                int result = 0;
    
                String inputString = String.valueOf(input);
    
    
                for (int i=0; i < inputString.length();i++){
    
                    int currentChar = inputString.charAt(i)- '1';
    
                    if((result &(1 << currentChar)) > 0){
                        return false;
                    }
    
                    result = result|(1 << currentChar);
    
            }
    
                return true;
            }
        }
    

提交回复
热议问题