My computer teacher wont explain why my code is complicated!!! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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); }

21st Jun 2019, 6:58 PM
Heisenberg
Heisenberg - avatar
10 Answers
+ 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); }
22nd Jun 2019, 9:58 AM
zemiak
+ 14
Muso iltimos, turli tillarda yozmang🙏. Agar sizga yordam kerak bo'lsa, bizga ma'lum bir savol bilan murojaat qilishingiz mumkin.
23rd Jun 2019, 5:02 PM
🅢🅗🅐🅡🅞🅕🇺🇿
🅢🅗🅐🅡🅞🅕🇺🇿 - avatar
+ 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)
21st Jun 2019, 9:39 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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
21st Jun 2019, 9:51 PM
Denise Roßberg
Denise Roßberg - avatar
22nd Jun 2019, 11:29 AM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Probably because the teacher doesn't know
22nd Jun 2019, 9:48 PM
Pet
+ 1
Men bu dasturdan foydalana olmayabman
24th Jun 2019, 12:36 PM
Muso
0
zemiak what do you mean with really recursive solution?
22nd Jun 2019, 10:08 AM
Denise Roßberg
Denise Roßberg - avatar
0
Qollanma bolsa tashang
24th Jun 2019, 12:37 PM
Muso
0
Siz bn qanday boglansam boladi
24th Jun 2019, 12:38 PM
Muso