加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Palindromes使用Scala

发布时间:2020-12-16 19:22:25 所属栏目:安全 来源:网络整理
导读:我遇到了这个 problem from CodeChef.问题陈述如下: A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not
我遇到了这个 problem from CodeChef.问题陈述如下:

A positive integer is called a palindrome if its representation in the
decimal system is the same when read from left to right and from right
to left. For a given positive integer K of not more than 1000000
digits,write the value of the smallest palindrome larger than K to
output.

我可以定义一个isPalindrome方法如下:

def isPalindrome(someNumber:String):Boolean = someNumber.reverse.mkString == someNumber

我面临的问题是,当整数满足isPalindrome方法时,如何从初始给定数字循环并中断并返回第一个回文?另外,是否有更好(有效)的方法来编写isPalindrome方法?

在这里获得一些指导会很棒

解决方法

如果您有一个像123xxx这样的数字,那么xxx必须低于321 – 那么下一个palindrom是123321.

或者xxx在上面,然后3不能保留,124421必须是下一个.

这里有一些没有保证的代码,不是很优雅,但中间(多个)Nines的情况有点多毛(19992):

object Palindrome extends App {

def nextPalindrome (inNumber: String): String = {
  val len = inNumber.length ()
  if (len == 1 && inNumber (0) != '9') 
    "" + (inNumber.toInt + 1) else {
    val head = inNumber.substring (0,len/2)
    val tail = inNumber.reverse.substring (0,len/2)
    val h = if (head.length > 0) BigInt (head) else BigInt (0)
    val t = if (tail.length > 0) BigInt (tail) else BigInt (0)

    if (t < h) {
      if (len % 2 == 0) head + (head.reverse)
      else inNumber.substring (0,len/2 + 1) + (head.reverse)
    } else {
     if (len % 2 == 1) {
       val s2 = inNumber.substring (0,len/2 + 1) // 4=> 4
       val h2 = BigInt (s2) + 1  // 5 
       nextPalindrome (h2 + (List.fill (len/2) ('0').mkString)) // 5 + "" 
     } else {
       val h = BigInt (head) + 1
       h.toString + (h.toString.reverse)
     }
    }
  }
}

def check (in: String,expected: String) = {
  if (nextPalindrome (in) == expected) 
    println ("ok: " + in) else 
    println (" - fail: " + nextPalindrome (in) + " != " + expected + " for: " + in)
}
//
val nums = List (("12345","12421"),// f
  ("123456","124421"),("54321","54345"),("654321","654456"),("19992","20002"),("29991","29992"),("999","1001"),("31","33"),("13","22"),("9","11"),("99","101"),("131","141"),("3","4")
)
nums.foreach (n => check (n._1,n._2))
println (nextPalindrome ("123456678901234564579898989891254392051039410809512345667890123456457989898989125439205103941080951234566789012345645798989898912543920510394108095"))

}

我想它也将处理一百万位Int的情况.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读