1

Can we reverse a string by using maths logic without using for loop logic(starting with len-1) or built-in functions

7
  • Is a while loop allowed? Or are any loop constructs forbidden? Is recursion allowed? Commented Jul 29, 2019 at 17:12
  • 1
    loop allowed but not that condition that we start from end of string and print charAt that, like in numbers we use that trick find modulous and divide ,can we do it with strings??? Commented Jul 29, 2019 at 17:15
  • You should print or get a new string at the end ? Commented Jul 29, 2019 at 17:16
  • Simran, you start a whileloop looping through the string char by char. YOU Check to see if the next char is null. If it's null, exit the loop. Else, create or append to an array with the current char (in the correct order so the string is reversed (that's just regular business logic)). Commented Jul 29, 2019 at 17:25
  • not a duplicate? reversing a string? Commented Jul 29, 2019 at 17:36

3 Answers 3

2

If recursion allowed:

public class Test {
    static void reverse(int pos, String str){
        if(pos==str.length()) return;
        reverse(pos+1, str);
        System.out.print(str.charAt(pos));
    }

    public static void main(String[] args) {
        String str = "what ever";
        reverse(0, str);  // here we start from position zero.
        System.out.println("");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this with strings with fixed size character, but you have to implement your custom bignumber which supports at least radix 256 (for 8 bit encoding, 65536 for 16 bit, etc).

Then you will be able to get modulo 256, divide and thus get reversed string as you do with numbers.

But, this approach will give you horrible performance, so use it just for fun.

Comments

-3

You can use apache StringUtils lib and use the reverse method as below.

StringUtils.reverse("abc");

It will return "cba".

1 Comment

"Without using built-in functions", I don't think using an external library meets the requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.