0

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

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

Palindrome 基本上是一个反转后具有相同值的数字,例如 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;
   }
}
4

1 回答 1

0

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

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;
}
于 2013-10-24T05:23:20.733 回答