What's the problem with this code? I want to take two strings in input, reverse the first and then compare it with the second. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

What's the problem with this code? I want to take two strings in input, reverse the first and then compare it with the second.

https://code.sololearn.com/cQV7aqZZl92w/?ref=app

23rd Nov 2019, 9:03 AM
Fau_zi
Fau_zi - avatar
2 Answers
+ 13
Check Line 11 of your code. You are going from end to start of the string and at the same time you are incrementing the counter. You need to decrement the value of i if you are traversing string from end to start. Just change that line to this : for(int i=leng-1; i>=0; i--)
23rd Nov 2019, 9:10 AM
Nova
Nova - avatar
+ 3
You could also use a for each loop: for(char c : a.toCharArray()){ res = c + res} for additional speed you could also append the chars to a StringBuilder instead of resizing the String every time, but this isn't necessary
23rd Nov 2019, 3:05 PM
Colath
Colath - avatar