我整晚都在试图回答这个问题,但我想我的大脑在期中考试中被烧焦了,无法正确回答这个问题。所以问题就被引用了:编写一个highLow方法,它接受一个整数作为参数,并返回该数字是否有交替的“高”和“低”数字。0到4是“低”数字,5到9是“高”数字。如果传递的数字在“高”和“低”数字之间交替,您的方法应该返回true,否则返回false。你可以假设传递的数字是正数。如果传递的数字由单个数字组成,则您的方法应返回true。
注意:如果数字以“高”数字开头或以“低”数字开头,则该方法返回true。重要的是数字是交替的。例如,highLow(9292)和highLow(2929)都应该返回true。
以下是对该方法的调用及其结果返回值的一些示例:
调用返回的值highLow(1918193) true highLow(7283) true highLow(3827) true highLow(9388) false highLow(895151) false highLow(707) true highLow(44) false highLow(45) true highLow(5) true您不能使用字符串来解决此问题
这是我最近的一次尝试:
public class Practeese {
public static void main(String[] args) {
highLow(1918193);
highLow(7283);
highLow(3827);;
highLow(9388);
highLow(895151);
highLow(707);
highLow(44);
highLow(45);
highLow(5);
}
public static boolean highLow(int n) {
// boolean isHigh = true;
// boolean isLow = true;
boolean test = true;
while (n > 0) {
boolean isHigh = true;
boolean isLow = true;
if (n % 10 >= 5) {
isHigh = true;
} else if (n%10<=5) {
isLow = true;
} else {
return false;
}
n = n / 10;
if (n % 10 == 0 && (isLow!= isHigh)) {
test = true;
} else {
test = false;
}
}
return test;
}
}我知道这是一个击剑式的问题,但我似乎能解决它..任何帮助都是非常感谢的。
发布于 2015-05-08 16:47:12
你只需要达到false一次,然后你就可以返回了-因为其他的数字都无关紧要。此外,您还需要检查结果是否为真-与之前的数字进行比较。所以你可以这样做:
public static boolean highLow(int n) {
boolean isLastHigh= n % 10 >= 5 ; //First number check - we don't compare it to anything
n=n/10;
// Start checking the next numbers and see if they are high-low-high-low
// if the condition is not met - return false and stop checking. Otherwise keep going
while (n > 0) {
if (n % 10 >= 5) {
if(isLastHigh)
return false; //Two highs in a row
isLastHigh = true;
} else {
if(!isLastHigh)
return false; //Two lows in a row
isLastHigh = false;
}
n = n / 10;
}
return true; //We never returned false so all numbers until now have been high-low-high and the result is true
}发布于 2015-05-08 17:28:16
这对我很有效
public class Practeese {
public static void main(String[] args) {
System.out.println(highLow(1918193));
System.out.println(highLow(7283));
System.out.println(highLow(3827));
System.out.println(highLow(9388));
System.out.println(highLow(895151));
System.out.println(highLow(707));
System.out.println(highLow(44));
System.out.println(highLow(45));
System.out.println(highLow(5));
}
public static boolean highLow(int n) {
boolean high = false;
boolean low = false;
while (n > 0) {
if(n % 10 >= 5) {
if(high) {
return false;
} else {
low = false;
high = true;
}
} else {
if(low) {
return false;
} else {
high = false;
low = true;
}
}
n = n / 10;
}
return true;
}
}输出: true false false true false true true
https://stackoverflow.com/questions/30119414
复制相似问题