【发布时间】:2018-03-23 11:02:23
【问题描述】:
我从朋友那里得到了一些伪代码形式的测试代码。他请我帮忙发帖。
这是伪代码:
function g(string str) returns string
int i =0
string new_str = ""
while i < len(str) - 1
new_str = new_str + str [i + 1]
i++
end
return new_str
end
function f(string str) return string
if len(str) == 0
return ""
else if len(str) == 1
return str
else
return f(g(str) + str [0]
end
end
function h(int n, string str) returns string
whlie n != 1
if n % 2 == 0
n = n/2
else
n = 3 * n + 1
end
str = f(str)
end
return str
end
function pow(int x, int y) returns int
if y == 0
return 1
else
return x * pow(x, y-1)
end
end
print (h(1, "fruits"))
print (h(2, "fruits"))
print (h(5, "fruits"))
print (h(pow(2, 1000000000000000), "fruits"))
print (h(pow(9831050005000007), "fruits"))
我尝试将其转换为 Java 语法,但在第 20 行和第 32 行出现错误:
不兼容的类型:字符串无法转换为字符串[]
这是我制作的代码:
public class TestLogic{
public String g(String[] str){
int i=0;
String new_str = "";
while(i < (str.length -1)){
new_str += str[1 + i];
i = i + 1;
}
return new_str;
}
public String f(String[] str){
if (str.length == 0) {
return "";
}
else if (str.length == 1){
return str.toString();
}
else {
return f(g(str)) + str [0];
}
}
public static String h (int n, String str){
while(n!=1){
if (n%2==0){
n= n/2;
}
else{
n =3*n +1 ;
}
str = f(str);
}
return str;
}
public static int pow(int x, long y){
if (y==0) {
return 1;
}
else{
return x * pow(x, y-1);
}
}
public static void main(String[] args) {
System.out.print(h(1, "fruits"));
System.out.print(h(2, "fruits"));
System.out.print(h(5, "fruits"));
System.out.print(h(pow(2, 1000000000000000l),"fruits"));
System.out.print(h(pow(2, 9831050005000007l),"fruits"));
}
}
在这里要明确一点,我不是程序员。而且我是 Java 和编程世界的新手。
【问题讨论】:
-
是的......................
-
g(str)正在返回一个不能传递给函数f的字符串 -
要么OP需要将所述String包装成一个String数组,要么改变函数定义。