且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 08:01:16

这是一个简短而甜蜜的版本 :)

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

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

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

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

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.