方法如下:
public static long repeatedString(String s, long n) {
int convertedLong = (int) n;
String repeated = new String(new char[convertedLong]).replace("\0", s);
System.out.println(repeated);
long numberOfAs = 0;
for (int i = 0; i < convertedLong; i++ )
{
if (repeated.charAt(i) == 'a')
{
numberOfAs += 1;
}
}
System.out.print(numberOfAs);
return numberOfAs;
}当参数n很小时,方法工作得很好,但是当它像1000000000000一样大时,它会抛出一个异常:
The literal 1000000000000 of type int is out of range发布于 2021-10-18 20:57:53
Java中的int类型可用于表示-2147483648到2147483647之间的任意整数。看起来你已经达到了int类型可以容纳的限制。考虑使用long。因为你使用的方法需要很长的时间。
来自:
int convertedLong = (int) n;至:
long convertedLong = n;发布于 2021-10-18 20:52:15
问题来了,因为您的convertedLong是int类型。为什么?
将其设置为long,并将i变量设置为long。
出现此错误是因为您仅通过1000000000调用该函数。
将L附加到它,以将其作为"long“传递,如
100000000000L否则它将被当作int。
发布于 2021-10-18 20:53:16
除非另有说明,否则java中的所有数字文字都被定义为int类型。因此,您需要做的是将文本定义为long,方法是向文本添加L后缀。
1000000000000L
另外,为什么要将long转换为int?想要破坏目的吗?
有关更多信息,请查看this问题
https://stackoverflow.com/questions/69622407
复制相似问题