While loop exiting before computation because of datatypes

后端 未结 3 1341
遇见更好的自我
遇见更好的自我 2021-01-28 09:37

My program specifications are as follows. 1. All four digits are different 2. The digit in the thousands place is three times the digit in the tens place 3. The number is odd. 4

3条回答
  •  抹茶落季
    2021-01-28 10:22

    I believe this can be simplified significantly by looking at the given inequalities, soemthing like

    // thousands + hundreds + tens + ones == 27
    // thousands = tens * 3, or tens = thousands / 3
    // thousands = 3, 6 or 9
    public static void main(String[] args) {
        // thousands = tens * 3; so it must be a multiple of 3.
        for (int thousands = 3; thousands < 10; thousands += 3) {
            for (int hundreds = 0; hundreds < 10; hundreds++) {
                if (hundreds == thousands) {
                    continue;
                }
                // thousands = tens * 3; so the reverse is also true
                int tens = thousands / 3;
                if (tens == hundreds) {
                    continue;
                }
                // All of the digits sum to 27.
                int ones = 27 - thousands - hundreds - tens;
                if (ones > 9 || ones % 2 != 0 || ones == tens
                        || ones == hundreds || ones == thousands) {
                    continue;
                }
                int val = (thousands * 1000) + (hundreds * 100) + (tens * 10)
                        + ones;
                System.out.println(val);
            }
        }
    }
    

    Of course, the output is still

    9738
    

提交回复
热议问题