1317. 将整数转换为两个无零整数的和『简单』

题目来源于力扣(LeetCode

一、题目

1317. 将整数转换为两个无零整数的和

题目相关标签:数学

提示:

2 <= n <= 10^4

二、解题思路

根据题目说明:存在多个有效解决方案时,可以返回其中任意一个

2.1 暴力法

  1. 从 1 开始遍历

  2. 判断 n - 1 的差中是否包含数字零

  3. 包含数字零时,使 1 向 n 每次加 1,再次判断两数是否均不包含数字零

  4. 两项均不包含数字零时,将两项数字存储到数组中,return

三、代码实现

3.1 暴力法

public static int[] getNoZeroIntegers(int n) {
    int[] result = new int[2];

    for (int i = 1; i < n; i++) {
        // 相加的两项数字均不能包含零
        if (!numContainZero(i) && !numContainZero(n - i)) {
            result[0] = i;
            result[1] = n - i;
            return result;
        }
    }
    return result;
}

// 判断一个数中是否包含数字零
public static boolean numContainZero(int num) {
    while (num != 0) {
        // num % 10 == 0 时说明 num 值必含有数字零
        if (num % 10 == 0) {
            return true;
        }
        num /= 10;
    }
    return false;
}

四、执行用时

4.1 暴力法

五、部分测试用例

public static void main(String[] args) {
//        int n = 2;  // output:{1, 1}
//        int n = 10000;  // output:{1, 9999}
//        int n = 11;  // output:{2, 9}
    int n = 4102;  // output:{111, 3991}
//        int n = 69;  // output:{1, 68}
//        int n = 1010;  // output:{11, 999}
    int[] result = getNoZeroIntegers(n);
    System.out.println(Arrays.toString(result));
}
posted @ 2020-05-11 22:49  知音12138  阅读(216)  评论(0编辑  收藏  举报