Select the appropriate code which reverses a word.

Select the appropriate code which reverses a word.
A.
Code:
public String reverse(String input)
{
	for (int i = 0; i < input.length(); i++) 
	{
            stk.push(input.charAt(i));
        }
	String rev = "";
	while (!stk.isEmpty())
	{
            rev = rev + stk.peek();
        }
	return rev;
}
B.
Code:
public String reverse(String input)
{
	for (int i = 0; i < input.length(); i++) 
	{
            stk.push(input.charAt(i));
        }
	String rev = "";
	while (!stk.isEmpty())
	{
            rev = rev + stk.pop();
        }
	return rev;
}
C.
Code:
public String reverse(String input)
{
	for (int i = 0; i < input.length(); i++) 
	{
            stk.push(input.charAt(i));
        }
	String rev = "";
	while (!stk.isEmpty())
	{
            rev = rev + stk.pop();
        }
}
D.
Code:
public String reverse(String input)
{
	for (int i = 0; i < input.length(); i++) 
	{
            stk.push(input.charAt(i));
        }
	String rev = "";
	while (!stk.isEmpty())
	{
            rev = rev + stk.pop();
	    stk.pop();
        }
	return rev;
}
 
Answer: B
Explanation: Although, it is possible to reverse the string without using stack, it is done by looping through the string from the end character by character.
In Java, it is also possible to use the StringBuilder and StringBuffer classes which have a built-in method 'reverse'.
Note its similarity to PalindromeTest.
 

Tìm kiếm

Back
Top