我整夜都在努力回答这个问题,但我认为我的大脑从中期开始就太烦躁,无法正确回答。因此,问题完全是[quoted]:
编写一个highLow方法,该方法接受一个整数作为参数,并返回该数字是否具有交替的“高”和“低”数字。 0到4是“低”数字,而5到9是“高”数字。如果传递的数字在“高”位和“低”位之间交替,则您的方法应返回true,否则返回false。您可以假设传递的数字为正。如果传递的数字由一位数字组成,则您的方法应返回true。

注意:如果数字以“高”数字开头或以“低”数字开头交替,则该方法返回true。重要的是数字要交替。例如,highLow(9292)和highLow(2929)都应返回true。

这是对该方法及其结果返回值的一些示例调用:

收回通话价值
highLow(1918193)是
highLow(7283)是
highLow(3827)是
highLow(9388)否
highLow(895151)假
highLow(707)是
highLow(44)错误
highLow(45)是
highLow(5)是
您可能无法使用String来解决此问题

这是我最近的尝试:

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


我知道这是一个栅栏式的问题,但我似乎可以解决它。

最佳答案

您只需输入一次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

     }

07-26 05:59