给出一个房间号,找到它所在的房间的地板java

时间:2017-02-12 15:15:55

标签: java algorithm puzzle

我遇到了一个问题,根据以下分布,我必须使用给定的房间号找到地板:

floor    rooms
1        1-5
2        6-15
3        16-20
4        21-30
5        31-35
6        36-45

。假设我给的房间号是" 37"程序应该说"楼层号是6"。虽然我已经给出了以下解决方案,但我自己觉得它不是一个好的解决方案。我相信如果楼层数增加,它可能会失败。

    int queryRoom = 37;
    int totalFloor = 6;

    int currentRm = 0;
    int floorInQuestion = 1; // staring floor

    while (floorInQuestion != totalFloor) {
        if (floorInQuestion % 2 != 0) {
            currentRm = currentRm + 5;
        } else {
            currentRm = currentRm + 10;
        }
        if (queryRoom <= currentRm)
            break;
        floorInQuestion++;
    }

    System.out.println(floorInQuestion);

1 个答案:

答案 0 :(得分:0)

您可以使用数学公式:

int queryRoom = 37;
queryRoom--; // create 0-based index

int a = queryRoom / 15;
int b = queryRoom % 15;

int floorInQuestion = (a * 2);
if(b < 5) floorInQuestion++;
else floorInQuestion += 2;