+ 5
My computer teacher wont explain why my code is complicated!!!
My teacher always complain that my code is complicated but she wont explain why in the freaking world it is complicated And i am fed up of it! So i am showing u two piece of code one Written by me and the other one by my teacher. Q)A program on recursion to find the reverse of a string. -> my code int reverse(String s,int i){ if(i==s.lenght()-1) // base case return s; else return ( reverse( s.substring(++i),i)+ (s.charAt(0)); } } -> teacher's code string sen;// contains the string to be reversed void reverse (String s, int i){ if(i<=length()-1){ s=sen.charAt(i)+s; reverse(s,i++); } else System.out.println(s); }
10 Antworten
+ 4
your code is better it is really recursive solution
-----
teacher's code use external variable sen and traverse string which is outside function, He must call it like
sen = "123456";
reverse("",0); // no return
and it is ugly !
-----
but you have bug in your code, in
return ( reverse( s.substring(++i),i)+ (s.charAt(0));
++i causes that reverse gets shrinking part of last part s and some chars are lost, eg:
"1234"
i=1 1:234 -> 234
i=2 23:4 -> 4
here you lost 3
correct is :
return reverse( s.substring(1),i)+ s.charAt(0);
but then i is not necessary and you can optimize it without i:
static String reverse(String s) {
if (s.length()==1)
return s;
else
return reverse( s.substring(1) ) +s.charAt(0);
}
+ 14
Muso iltimos, turli tillarda yozmang🙏. Agar sizga yordam kerak bo'lsa, bizga ma'lum bir savol bilan murojaat qilishingiz mumkin.
+ 6
Another aspect:
Your method returns a String. It should be String reverse() not int reverse().
If you return a value you don't need an else statement.
if(i == s.length() - 1){
return s -> jump out of the method
But do you really need to return a String? (Your teacher prints the String)
+ 4
Heisenberg
Another aspect of your teachers code:
Using void -> print String
Why? There is no need to create a String. Just start at the last index and print the char at this index. If index < 0 return.
Here is my code:
https://code.sololearn.com/ccVbkDyuQQyi/?ref=app
+ 2
Muso Please don't spam.
https://www.sololearn.com/discuss/1316935/?ref=app
+ 2
Probably because the teacher doesn't know
+ 1
Men bu dasturdan foydalana olmayabman
0
zemiak what do you mean with really recursive solution?
0
Qollanma bolsa tashang
0
Siz bn qanday boglansam boladi