【数学】C029_将整数转为两个无零整数的和(枚举 (字符串处理) | 取数位)

一、题目描述

Given an integer n. No-Zero integer is a positive integer
which doesn't contain any 0 in its decimal representation.
Return a list of two integers [A, B] where:

A and B are No-Zero integers.
A + B = n
It's guarateed that there is at least one valid solution.
If there are many valid solutions you can return any of them.

Example 1:
Input: n = 2
Output: [1,1]
Explanation: A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation.

Example 5:
Input: n = 1010
Output: [11,999]

二、题解

(1) 暴力枚举(字符串处理)

public int[] getNoZeroIntegers(int n) {
  for (int i = 1; i < n; i++) {
  //if((i+"").indexOf("0") < 0 && ((n-i) + "").indexOf("0") < 0)
    if(!String.valueOf(i).contains("0") && !String.valueOf(n-i).contains("0"))
	  return new int[] {i, n-i};
  }
  return new int[2];
}

(2) 数位计算

public int[] getNoZeroIntegers(int n) {
  for (int i = 1; i < n; i++)
   if(isValid(i) && isValid(n-i))
    return new int[] {i, n-i};
  return new int[2];
}

private boolean isValid(int n) {
  while(n != 0) {
    if(n % 10 == 0) 
   	  return false;
    n /= 10;
  }
  return true;
}
发布了299 篇原创文章 · 获赞 48 · 访问量 7618
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览