在矩形网格的边缘找到一个单元格

时间:2015-01-27 17:50:28

标签: java

如果n位于矩形网格的边缘(numRows X numCols),则方法public static boolean onEdge(int n,int numRows,int numCols)应该为TRUE,如果n在内部,则为false。例如,(0,4,4)应该给出真或(2,4,4)也为真;但是(6,4,4)是假的。

public static boolean onEdge(int n, int numRows, int numCols) 
  {
      int originalRow = 0;

      if ((n < 0) || (numRows < 0) || (numCols < 0))
          return false;

      else if (n == originalRow) 
          return true;

      else if (n == numRows)
          return true;

      else
          return false;


  }

1 个答案:

答案 0 :(得分:1)

你可以使用简单的算术:

public static boolean onEdge(int n, int numRows, int numCols)
{
    int row = n / numCols; // int / int divides to floor
    int column = n % numCols; // column within row

    // check if n is in the beginning or final row
    if (row == 0 || row == numRows - 1)
        return true;

    // check if n is in the first or last column
    if (column == 0 || column == numCols -1)
        return true;

    return false;
}

您可以通过将n除以您拥有的列数来找到行号nint / int始终返回int值,即一(3/2 = 1)。

您可以通过使用模运算符获取上述除法的其余部分来找到列号n

如果您同时拥有这两个值,则可以检查n是在第一行还是最后一行或第一列或最后一列。如果没有,它就在你的领域的“中间”。

相关问题