处理大量数据
我遇到这个问题:
如果从左到右和从右到左读取时,正整数在十进制系统中的表示相同,则称为回文。对于给定的不超过1000000
位的正整数K
,将大于K
的最小回文数写入输出。显示的数字始终不带前导零。 输入
第一行包含整数t
,即测试用例的数量。整数 K
在接下来的 t
行中给出。 输出
对于每个K
,输出大于K
的最小回文。 示例
输入:
2
808
2133
输出:
818
2222
我的代码将输入转换为字符串,并评估字符串的任一端,相应地进行调整并向内移动。但是,问题要求它可以采用长达 10^6 位的值,如果我尝试解析大数字,我会收到数字格式异常,即
Integer.parseInt(LARGENUMBER);
or
Long.parseInt(LARGENUMBER);
并且 LARGENUMBER
超出范围。谁能想到解决方法或如何处理如此大的数字?
I have this problem:
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. Numbers are always displayed without leading zeros.
Input
The first line contains integer t
, the number of test cases. Integers K
are given in the next t
lines.
Output
For each K
, output the smallest palindrome larger than K
.
Example
Input:
2
808
2133
Output:
818
2222
My code converts the input to a string and evaluates either end of the string making adjustments accordingly and moves inwards. However, the problem requires that it can take values up to 10^6 digits long, if I try to parse large numbers I get a number format exception i.e.
Integer.parseInt(LARGENUMBER);
or
Long.parseInt(LARGENUMBER);
and LARGENUMBER
is out of range. can anyone think of a work around or how to handle such large numbers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能可以使用 BigInteger 类来处理像这样的大整数。
然而,我不指望它在如此大的尺寸下保持高效。因为它仍然使用
O(n^2)
算法进行乘法和转换。You could probably use the BigInteger class to handle large integers like this.
However, I wouldn't count on it being efficient at such massive sizes. Because it still uses
O(n^2)
algorithms for multiplication and conversions.想想你现在所做的步骤。由于您将数字转换为字符串来处理它,您是否看到一些看起来有点多余的东西?
Think of your steps that you do now. Do you see something that seems a little superfluous since you're converting the number to a string to process it?
虽然这个问题讨论的是整数,但这样做只是为了限制输入和输出的字符和格式。这确实是一道需要仔细选择的字符串运算题。既然是这种情况,您实际上不需要将输入实际读取为整数,而只需读取字符串。
这将使回文验证变得简单。您唯一需要解决的问题是选择下一个更高的。
While this problem talks about integers, its doing so only to restrict the input and output characters and format. This is really a string operations question with careful selection. Since this is the case, you really don't need to actually read the input in as integers, only strings.
This will make validating the palindrome simple. The only thing you should need to work out is choosing the next higher one.