Java 将int转换为字符串可以减少计算其长度的时间复杂性
以下代码块:Java 将int转换为字符串可以减少计算其长度的时间复杂性,java,algorithm,time-complexity,Java,Algorithm,Time Complexity,以下代码块: Scanner in=new Scanner(System.in); int n=in.nextInt(); //converting the integer to string and calculating //its length reduces the complexity //to O(n) as compared to O(n^2) String str=Integer.toString(n); int length=str.length();length-=1; 我
Scanner in=new Scanner(System.in);
int n=in.nextInt();
//converting the integer to string and calculating
//its length reduces the complexity
//to O(n) as compared to O(n^2)
String str=Integer.toString(n);
int length=str.length();length-=1;
我找到了
我的问题是,将int改为string如何降低时间复杂性?该代码的作者声称,与发布的另一个解决方案相比,它降低了复杂性:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num,d,rev=0;
cin>>num;
// reverse a no.
while(num!=0)
{
d=num%10;
rev=rev*10+d;
num=num/10;
}
// using digits of reversed no.
while(rev!=0)
{
d=rev%10;
cout<<d*d; // printing square
rev=rev/10;
}
return 0;
}
#包括
使用名称空间std;
int main()
{
int num,d,rev=0;
cin>>num;
//倒转一个号码。
while(num!=0)
{
d=num%10;
rev=rev*10+d;
num=num/10;
}
//使用反向编号的数字。
while(rev!=0)
{
d=版本%10;
cout该代码的作者声称,与发布的另一个解决方案相比,它降低了复杂性:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num,d,rev=0;
cin>>num;
// reverse a no.
while(num!=0)
{
d=num%10;
rev=rev*10+d;
num=num/10;
}
// using digits of reversed no.
while(rev!=0)
{
d=rev%10;
cout<<d*d; // printing square
rev=rev/10;
}
return 0;
}
#包括
使用名称空间std;
int main()
{
int num,d,rev=0;
cin>>num;
//倒转一个号码。
while(num!=0)
{
d=num%10;
rev=rev*10+d;
num=num/10;
}
//使用反向编号的数字。
while(rev!=0)
{
d=版本%10;
cout即使使用简单的查找整数的长度,而循环是O(n),而不是O(n^2)
考虑以下代码段:
while(n!=0)
{
n/=10;
++count;
}
即使使用简单的查找整数的长度,而循环也是O(n),而不是O(n^2)
考虑以下代码段:
while(n!=0)
{
n/=10;
++count;
}
我投票以离题方式结束这个问题,因为它要求解释某个随机人在互联网上的错误陈述。我投票以离题方式结束这个问题,因为它要求解释某个随机人在互联网上的错误陈述。