题目
给定
[a,b,c,d]
表示两个点的4个整数的数组,(a, b)
和(c, d)
返回连接这两个点的线的斜率的字符串表示。
对于未定义的斜率(除以0),返回 undefined
。请注意,“undefined”区分大小写。
a:x1
b:y1
c:x2
d:y2
假设[a,b,c,d]
答案都是整数(没有浮点数!)。坡度:https://en.wikipedia.org/wiki/Slope
测试用例:
import static org.junit.Assert.*;
import org.junit.Test;
public class SlopeTest
{
@Test
public void test1()
{
int[] test1={19,3,20,3};
Slope s=new Slope();
assertEquals("0",s.slope(test1));
assertEquals("undefined",s.slope(new int[]{-7,2,-7,4}));
assertEquals("5",s.slope(new int[]{10,50,30,150}));
assertEquals("-5",s.slope(new int[]{15,45,12,60}));
assertEquals("6",s.slope(new int[]{10,20,20,80}));
assertEquals("undefined",s.slope(new int[]{-10,6,-10,3}));
}
}
解题
My
public class Slope
{
public String slope(int[] points)
{
if((points[2]-points[0])==0) {
return "undefined";
}else{
return String.valueOf((points[3]-points[1]) / (points[2]-points[0]));
}
}
}
Other
public class Slope
{
public String slope(int[] points)
{
int nominator = points[3] - points[1], denominator = points[2] - points[0];
return denominator == 0 ? "undefined" : String.format("%s", (nominator) / (denominator));
}
}
后记
看到别人的解答,确实很实战啊。