java 检查整数是否有重复数字。没有字符串方法或数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26748026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:32:04  来源:igfitidea点击:

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

javaloopswhile-loopint

提问by Nobody

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 hasDistinctDigits(). It works when the repeating digits are at the end, but not when they come at the beginning or middle.

我正在尝试查看 int 是否具有相同数字的倍数。尝试在没有字符串方法或数组的情况下执行此操作。我遇到问题的主要方法是hasDistinctDigits(). 当重复数字位于末尾时它起作用,但当它们出现在开头或中间时不起作用。

public static void main(String[] args) {
    System.out.println(hasDistinctDigits(12234));
}

public static boolean hasDistinctDigits(int number) {
    boolean returner = true;
    int count = 1;
    int newNum = number;
    int digit = 0;

    while (count < numDigits(number)) {         
        while (count < numDigits(newNum)) {
            digit = newNum % 10;
            newNum/=10;
            if (digit == getDigit(newNum, count)) {
                returner = false;
            }
            count++;                
        }
        count++;
    }
    return returner;
}

public static int numDigits(int number) {
    int count = 0;
    while (number != 0) {
        number /= 10;
        count++;
    }
    return count;
}

public static int getDigit(int number, int i) {
    int digit = 0;
    int count = 0;
    int originalNum = number;

    while (count <= i) {
        if (count == i) {
            digit = number % 10;
        }
        number /= 10;
        count++;
    }
    if (i > numDigits(originalNum)) {
        return -1;
    } else {
        return digit;
    }
}

}

}

If this is run, you will see '2' repeats itself, but the method still evaluates to truewhen it should be false.

如果运行此命令,您将看到 '2' 自我重复,但该方法仍会评估为true应为 的时间false

回答by xpa1492

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. numMaskis 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).

它的工作方式非常简单。numMask是一个整数,用于存储已经遇到的数字(因为十进制系统数字只有 10 位,而整数使用 16 位,我们有足够的位来存储每个十进制数字出现时)。

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 5in the past, so we can immediately tell that the number does not have all distinct digits and return false; otherwise, we modify numMaskand raise the 5th bit.

我们遍历数字中的所有数字。对于每个数字索引,我们在curDigit. 假设当前数字是5。然后我们检查numMask中第5位是否被提出:如果是,那么我们过去已经遇到a 5,所以我们可以立即判断该数字没有所有不同的数字并返回false;否则,我们修改numMask并提高第 5 位。

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

如果我们坚持到最后,则不会遇到重复数字。

回答by Tanmay Patil

You need to check each digit with every other digit. This suggests that you should have at least two nested loops. You seem to have mixed them both.

您需要将每个数字与其他数字进行核对。这表明您应该至少有两个嵌套循环。你似乎把它们都混在一起了。

Have one loop for the digit being checked and other for iterating over all other digits.

有一个循环用于被检查的数字,另一个循环用于迭代所有其他数字。



Also, your getDigitmethod is not working correctly. Replace it with

此外,您的getDigit方法无法正常工作。将其替换为

public static int getDigit(int number, int i) {
    int digit = 0;
    int count = 0;
    int originalNum = number;

    while (count <= i) {
        if (count == i) {
            digit = number % 10;
        }
        number /= 10;
        count++;
    }
    if (i > numDigits(originalNum)) {
        return -1;
    } else {
        return digit;
    }
}

Hope this helps. Good luck.

希望这可以帮助。祝你好运。

回答by learner

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.

此处可以使用相同的逻辑来验证字符串是否具有唯一字符。(1 << currentChar) ,它将 currentChar 中的位设置为 1 等于该索引处存在的数字(0-9),并且所有其他位都设置为 0。

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

(result &(1 << currentChar) : 如果位已经设置为 1 则返回 false 否则

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

result = result|(1 << currentChar):设置结果整数中的位,该位等于该索引处的数字。

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;
        }
    }

回答by Densil D'silva

public static boolean hasDistinctDigits(int number) {
         int numMask = Math.floorMod(number, 10);
         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;
             if(numMask != curDigit)  return false;
             numMask = numMask & curDigit;
         }
         return true;
    }