我正在解决 JavaBat 问题,但对我的逻辑感到困惑。
任务如下:
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".
alarmClock(1, false) → "7:00" alarmClock(5, false) → "7:00" alarmClock(0, false) → "10:00"
这是我的代码:
public String alarmClock(int day, boolean vacation) {
if ( (day >=1 && day <=5) && (!vacation)) {
return "7:00";
} else if ( (day >=1 && day <=5) && (vacation)) {
return "10:00";
} else {
return "off";
}
}
为什么这两个测试失败?
alarmClock(0, false) → "10:00""off"X
AlarmClock(6, false) → "10:00""off"X
当然,这一行涵盖了它?
if (天 >=1 && 天 <=5) && (!假期))
最佳答案
这个怎么样?
public String alarmClock(int day, boolean vacation) {
if (day >=1 && day <=5) {
return vacation ? "10:00" : "7:00";
} else {
return vacation ? "off" : "10:00";
}
}
请注意,这确实取决于您的编码约定是否允许使用旋转运算符。但在这种情况下,我认为逻辑更容易阅读。
关于Javabat帮助: alarmClock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8491894/