【问题标题】:Find the even number using given number使用给定的数字找到偶数
【发布时间】:2018-06-23 16:27:27
【问题描述】:

我必须使用给定数字的位数找到最大的偶数

输入: 7876541
所需输出: 8776514

谁能帮我解释一下逻辑?

【问题讨论】:

  • 请发布您现在拥有的代码..
  • 8776514 不正确,因为8776541 最大。
  • @Rao,感谢您的快速帮助,但在输出中我需要最大的偶数
  • @RitaR,请查看EDIT 部分。

标签: groovy soapui


【解决方案1】:

无需创建排列。 试试这个解决方案:

  • 将源编号转换为字符串。
  • 将字符串拆分成数组,
  • 暂时按升序对数字进行排序,
  • 找到第一个偶数的索引,
  • 从数组中删除此数字(将其存储在变量中),
  • 反转数组并添加删除的数字,
  • 连接数组中的数字并将它们转换为整数。

所以整个脚本如下所示:

def inp = 7876541
def chars1 = inp.toString().split('')
// findAll{it} drops an empty starting element from the split result
def chars2 = chars1.findAll{it}.sort()
// Find index of the 1st even digit
def n = chars2.findIndexOf{it.toInteger() % 2 == 0}
def dig = chars2[n]     // Store this digit
chars2.remove(n)        // Remove from the array
def chars3 = chars2.reverse()   // Descending order
chars3.add(dig)         // Add the temporarily deleted number
def out = (chars3.join()) as Integer    // result
println out

【讨论】:

    【解决方案2】:

    这个怎么样?

    • 转成字符串
    • 倒序排列数字
    • 加入他们并将其转换为数字
    def n = 7876541
    def newN = (n.toString().split('').findAll{it}.sort().reverse().join()) as Integer
    println newN
    

    你可以快速上线试用demo

    编辑:基于 OP cmets,更新答案。

    这是你可以做的 -
    - 找到数字的排列
    - 找到偶数
    - 按最大数量过滤。

    已经找到thread 用于查找排列,因此只需稍加改动即可重新使用它。感谢JavaHopper

    当然可以通过groovified来简化。

    class Permutations {
      static def list = []
      public static void printPermutation(char[] a, int startIndex, int endIndex) {
        if (startIndex == endIndex)
            list << ((new String(a)) as Integer)
        else {
            for (int x = startIndex; x < endIndex; x++) {
                swap(a, startIndex, x)
                printPermutation(a, startIndex + 1, endIndex)
                swap(a, startIndex, x)
            }
        }
      }
      private static void swap(char[] a, int i, int x) {
        char t = a[i]
        a[i] = a[x]
        a[x] = t
      }
    
    }
    def n = 7876541
    def cArray = n.toString().toCharArray()
    Permutations.printPermutation(cArray, 0, cArray.size())
    println Permutations.list.findAll { it.mod(2) == 0}?.max()
    

    赶紧上网试试demo

    【讨论】:

    • "$n".chars.toList().permutations()*.join()*.toInteger().findAll { it % 2 == 0 }.max() ;-) 更少的代码ftw! ;-)
    • @RitaR,如果你接受它为answered,将不胜感激
    • @Rao,我没有得到标记为已回答的选项。 :(
    猜你喜欢
    • 2021-12-28
    • 2012-09-02
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多