查找边界之间的回文整数数量 - Java 调试



下面的代码有风格缺陷和一两个错误。尽可能多地列出缺陷。

public int palindromeCount (int start, int finish) {
   int k = start;
   int returnVal = 0;
    while (k<finish) {
      int temp = k;
      int r = 0;
      while (temp > 0) {
         r = 10 * r + temp%10;
         temp = temp/10;
      }
      if (r == k) {
         returnVal++;
      }
      k++;
   }
   return returnVal;
}

回文基本上是一个数字,如果反转,则具有相同的值,例如 11。这里的代码需要浏览一个范围,最后得到该范围内的回文数量。我这样做是为了学习循环。

这是我的进步:

public class Counter{
   public Counter(){
  }
   public int palindromeCount (int start, int finish) {
      int returnVal = 0;
      int temp = start;
      while (start < finish) {
         int reverse = 0;
         while (temp != 0) {
           reverse = 10 * reverse + temp % 10;
            temp = temp/10;
         }
         if (temp == start) {
            returnVal = returnVal + 1;
         }
         start = start + 1;
      }
      return returnVal;
   }
}
我想

你之前发布过这个,据我测试过,它运行良好。

public static int palindromeCount(int start, int finish) {
    int k = start;
    int returnVal = 0;
    while (k <= finish) { // Changed to <= to consider "finish" too
        int temp = k;
        int r = 0;
        while (temp > 0) {
            r = 10 * r + temp % 10;
            temp = temp / 10;
        }
        if (r == k) {
            returnVal++;
        }
        k++;
    }
    return returnVal;
}

最新更新