Codewars里的 7kyu Kata。
题目说明:
Have you heard about the myth that if you fold a paper enough times, you can reach the moon with it? Sure you do, but exactly how many? Maybe it's time to write a program to figure it out.
You know that a piece of paper has a thickness of
0.0001m
. Givendistance
in units of meters, calculate how many times you have to fold the paper to make the paper reach this distance.
(If you're not familiar with the concept of folding a paper: Each fold doubles its total thickness.)Note: Of course you can't do half a fold. You should know what this means ;P
Also, if somebody is giving you a negative distance, it's clearly bogus and you should yell at them by returning
null
(or whatever equivalent in your language. In Shell please returnNone
).
这一张厚度为 0.0001m 的纸到目标值。求折叠的次数。
解题代码:
public class PaperFolder {
public static Long fold(Double distance) {
if (distance < 0)
return null;
if (distance < 0.0001)
return new Long(0);
double dis = Double.valueOf(distance);
long res = 0;
while (dis > 0.0001) {
dis /= 2;
res++;
}
return new Long(res);
}
}
Test Cases:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.lang.Math;
import java.util.Random;
public class SolutionTest {
public static Long solution(Double distance) {
if (distance < 0)
return null;
if (distance < 0.0001)
return Long.valueOf(0L);
String str = Double.toString(Math.ceil(Math.log(distance * 10000) / Math.log(2)));
str = str.substring(0, str.indexOf("."));
Long answer = new Long(str);
return answer;
}
@Test
public void sampleTests() {
assertEquals(Long.valueOf(42L), PaperFolder.fold(new Double(384000000)));
assertEquals(Long.valueOf(0L), PaperFolder.fold(new Double(0.00005)));
}
@Test
public void additionalTests() {
assertEquals(Long.valueOf(4L), PaperFolder.fold(new Double(0.0016)));
assertEquals(Long.valueOf(5L), PaperFolder.fold(new Double(0.0032)));
assertEquals(Long.valueOf(0L), PaperFolder.fold(new Double(0.0000001)));
assertEquals(Long.valueOf(0L), PaperFolder.fold(new Double(0)));
assertEquals(null, PaperFolder.fold(new Double(-1)));
}
@Test
public void randomTests() {
Random rand = new Random();
for (int i = 0; i < 1000; i++) {
Double d = new Double(Math.pow(rand.nextDouble(), (double) (rand.nextInt(20) - 10)));
String message = "Testing " + d;
assertEquals(message, SolutionTest.solution(d), PaperFolder.fold(d));
}
}
@Test
public void invalidParameter() {
assertEquals(null, PaperFolder.fold(new Double("-1")));
}
}
个人总结:
Very Interesting Kata! 如果厚度为整型的话直接位运算是否会更快呢?