后续行动:如何显示可以从一串数字中创建的所有IP地址组合? [英] Follow-up:How to show all combinations of IP address that can be created from a string of numbers?
问题描述
这是这个问题。
我需要将输入字符串格式化为IP地址格式,所以我有以下代码;但是,问题是它提供了所有的组合,但是我需要找到每个组合不超过255个。
I need to format the input string into IP address format, so I have the following code; however, the problem is that it is providing all the combinations but I need to find those that each of their groups in not more than 255.
问题:从提供的字符串19216801 ,我想你不能确定确切的ip。它可以是192.168.0.1或19.216.80.1或任何其他组合?
Question: From provided string 19216801, I think you can't identify exact ip. It can be 192.168.0.1 or 19.216.80.1 or any other combination?
答案:我不是在寻找任何特定的IP我只需要显示所有可能的组合他们的群组不超过255个。
Answer: I am not looking for any specific IP I just need to show all the possible combinations that their groups are not more than 255.
代码
String number = "19216801";
int l = number.length() - 3;
for(int a = 0; a < l; a++) {
for(int b = 0; b < l-a; b++){
for(int c = 0; c <l-a-b; c++){
StringBuilder sb = new StringBuilder(number);
sb.insert(a+1, ".");
sb.insert(a+b+3, ".");
sb.insert(a+b+c+5, ".");
System.out.println(sb);
}
}
}
推荐答案
这似乎起作用:
String number = "19216801";
// Digits in 1st number.
for (int a = 1; a <= 3; a++) {
for (int b = 1; b <= 3; b++) {
for (int c = 1; c <= 3; c++) {
for (int d = 1; d <= 3; d++) {
if (a + b + c + d == number.length()) {
int n0 = Integer.parseInt(number.substring(0, a));
int n1 = Integer.parseInt(number.substring(a, a + b));
int n2 = Integer.parseInt(number.substring(a + b, a + b + c));
int n3 = Integer.parseInt(number.substring(a + b + c, a + b + c + d));
if (n0 >= 0 && n0 <= 255
&& n1 >= 0 && n1 <= 255
&& n2 >= 0 && n2 <= 255
&& n3 >= 0 && n3 <= 255) {
System.out.println(n0 + "." + n1 + "." + n2 + "." + n3 + ".");
}
}
}
}
}
}
打印
1.92.168.1.
19.2.168.1.
19.21.68.1.
19.216.8.1.
19.216.80.1.
192.1.68.1.
192.16.8.1.
192.16.80.1.
192.168.0.1.
另外 - 如果前导零表示无效:
Alternatively - if leading zeros indicates an invalid:
public void test() {
String number = "19216801";
// Digits in 1st number.
for (int a = 1; a <= 3; a++) {
for (int b = 1; b <= 3; b++) {
for (int c = 1; c <= 3; c++) {
for (int d = 1; d <= 3; d++) {
if (a + b + c + d == number.length()) {
String s0 = number.substring(0, a);
String s1 = number.substring(a, a + b);
String s2 = number.substring(a + b, a + b + c);
String s3 = number.substring(a + b + c, a + b + c + d);
if (good(s0) && good(s1) && good(s2) && good(s3)) {
int n0 = Integer.parseInt(s0);
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int n3 = Integer.parseInt(s3);
if (good(n0) && good(n1) && good(n2) && good(n3)) {
System.out.println(n0 + "." + n1 + "." + n2 + "." + n3);
}
}
}
}
}
}
}
}
private boolean good(String s) {
// Not allowed to remove leading zeros.
return s.length() == 1 || s.charAt(0) != '0';
}
private boolean good(int n) {
// Between 0 and 255
return n >= 0 && n <= 255;
}
打印
19.216.80.1.
192.16.80.1.
192.168.0.1.
这篇关于后续行动:如何显示可以从一串数字中创建的所有IP地址组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!