我想解决Topcoder中的一个问题,我需要在提供宽度和长度时找到矩形的数量(不包括正方形)。我的代码适用于所有测试用例,但对于最后一个测试用例,即592X964
,我需要返回81508708664
,这大于2^32-1
,这大于long可容纳的值,但编译器要求必须返回值long
。我已经添加了下面的问题陈述和我的代码,请好好理解一下,并让我知道是否有可能在java中使用long来返回上述值。当返回值大于long时,如何从方法返回long?
/*
Problem Statement
Given the width and height of a rectangular grid, return the total number of rectangles (NOT counting squares) that can be found on this grid.
For example, width = 3, height = 3 (see diagram below):
__ __ __
|__|__|__|
|__|__|__|
|__|__|__|
In this grid, there are 4 2x3 rectangles, 6 1x3 rectangles and 12 1x2 rectangles. Thus there is a total of 4 + 6 + 12 = 22 rectangles. Note we don't count 1x1, 2x2 and 3x3 rectangles because they are squares.
Definition
Class:
RectangularGrid
Method:
countRectangles
Parameters:
int, int
Returns:
long
Method signature:
long countRectangles(int width, int height)
(be sure your method is public)
Limits
Time limit (s):
2.000
Memory limit (MB):
64
Notes
-
rectangles with equals sides (squares) should not be counted.
Constraints
-
width and height will be between 1 and 1000 inclusive.
Examples
0)
3
3
Returns: 22
See above
1)
5
2
Returns: 31
__ __ __ __ __
|__|__|__|__|__|
|__|__|__|__|__|
In this grid, there is one 2x5 rectangle, 2 2x4 rectangles, 2 1x5 rectangles, 3 2x3 rectangles, 4 1x4 rectangles, 6 1x3 rectangles and 13 1x2 rectangles. Thus there is a total of 1 + 2 + 2 + 3 + 4 + 6 + 13 = 31 rectangles.
2)
10
10
Returns: 2640
3)
1
1
Returns: 0
4)
592
964
Returns: 81508708664
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
*/
public class RectangularGrid
{
public static void main(String[] args)
{
System.out.println(countRectangles(592,964));
}
public static long countRectangles(int m, int n)
{
long tot_rect = (long)(((m*m)+m)*((n*n)+n))/4;
long tot_square = 0;
boolean status = true;
while(status)
{
if(m>0 && n>0)
{
tot_square+=(long)m*n;
--m;
--n;
}
else
{
status = false;
}
}
return tot_rect-tot_square;
}
}
“长”是2^63-1。 – chrylis
为什么不使用'BigDecimal',假设你真的无法将值存储在'long'(你可以)? –
“长”是64位,因此它可以保存-2^63和2^63 - 1之间的值;你认为它不能保持大于2^32 - 1的值是错误的。 – Jesper