我有一个java问题,我必须看看9位数字是否只包含1,2,3 - 并且还有1和2的相同数字3,反之亦然。
例如:
答案 0 :(得分:0)
private boolean onlyContainsOneTwoAndThree(int number) {
char[] digitsFromNumber = String.valueOf(number).toCharArray(); // convert to char[] for easier manipulation.
int oneCounter = 0;
int twoCounter = 0;
int threeCounter = 0;
for (char digit : digitsFromNumber) {
switch (digit) {
case '1':
oneCounter++;
break;
case '2':
twoCounter++;
break;
case '3':
threeCounter++;
break;
default:
return false;
}
}
if ((oneCounter == twoCounter) && (twoCounter == threeCounter)) {
return true; // return true only when 1,2 and 3 appear exactly the same number of times.
}
return false;
}
答案 1 :(得分:0)
boolean correct(String input) {
Map<Character, Integer> map = new HashMap<>();
char[] charArray = input.toCharArray();
for (char num : charArray) {
Integer count = map.get(num);
if (count == null) {
count = 0;
}
map.put(num, count.intValue() + 1);
}
Integer val = map.get('1');
if (val != null && val == map.get('2') && val == map.get('3') &&
map.size() == 3) {
return true;
}
return false;
}
答案 2 :(得分:0)
public static boolean isGood(String input) {
return input.length() == 9 && 2D == input.chars()
.parallel()
.mapToObj(i -> (char)i)
.map(Character::getNumericValue)
.map(number -> number >= 1 && number <= 3 ? number : Integer.MAX_VALUE)
.mapToInt(number -> number).average().orElse(-1);
}
答案 3 :(得分:-1)
String s = Integer.toString(number);
System.out.println(s.contains("1") && s.contains("2") && s.contains("3"));