java - 如何生成 2 位远程 PIN 码?
问题描述
我想生成彼此相距至少 2 位的 4 位 PIN 码。
例如:
- 5235和4068都可以
- 5235和5339都可以
- 5235和2553都可以
- 5235 和 5236 不行
- 5325 和 5235 不行(排列)
排列很容易检查,但如何检查距离?
解决方案
逻辑如下:
- 检查pin1是否是排列
/
使用,检查 pin1 的每个数字与 pin2 相同位置的数字%
。- 计算相同数字的数量。
- 根据它们的数量返回真/假。
假设您有办法检查排列,这里有一个完整的解决方案:
class Solution {
public static void main(String[] args) {
/*
* 5235 and 4068 is OK
* 5235 and 5339 is OK
* 5235 and 2553 is OK
* 5235 and 5236 is NOT OK
* 5325 and 5235 is NOT OK (permutation)
*/
// threshold is the maximum number of digits that can be the same
// while the pin1, pin2 are distant enough; in this case 2
int threshold = 2;
int pinLength = 4;
System.out.println(areDistant(5235, 4068, threshold, pinLength));
System.out.println(areDistant(5235, 5339, threshold, pinLength));
System.out.println(areDistant(5235, 2553, threshold, pinLength));
System.out.println(areDistant(5235, 5236, threshold, pinLength));
System.out.println(areDistant(5325, 5235, threshold, pinLength));
}
public static boolean areDistant(int pin1, int pin2, int threshold, int pinLength) {
if (isPermutation(pin1, pin2))
return false;
int sameDigits = 0;
int ithDigit1, ithDigit2;
for (int i=0; i<pinLength; i++) {
ithDigit1 = (int) (pin1 / Math.pow(10, i)) % 10;
ithDigit2 = (int) (pin2 / Math.pow(10, i)) % 10;
// System.out.println(ithDigit1);
// System.out.println(ithDigit2);
if ( ithDigit1 == ithDigit2)
sameDigits += 1;
}
return sameDigits <= threshold;
}
private static boolean isPermutation(int pin1, int pin2) {
return false;
// fill the code here
}
}
推荐阅读
- angular - 如何在动态插入图像源的角度 2 中使用 onload 事件
- angular - angular-material:如何控制活动高亮颜色条的位置
- android - 我禁用了电话呼叫者视图的全屏,但如何禁用此视图?
- postgresql - 如何在 Windows 上无头(无终端)启动 postgres 服务器?
- android - 如何设置反应原生元素的尺寸以在不同的设备英寸尺寸中显示相同的尺寸
- linux - 我们可以复制curl包并在不安装的情况下在Linux上运行吗
- python - 使用python将时间设置为0,在特定列中具有值
- c++ - 循环速度更快,限制固定
- spring - Spring控制器不加载视图
- hibernate - 休眠二级缓存不适用于 GORM 6.1.11