`
xiatiaohcx
  • 浏览: 31773 次
  • 性别: Icon_minigender_1
  • 来自: 山西
社区版块
存档分类
最新评论

java面试——逆序打印

阅读更多

公司程序员面试经常碰到的题

1.String的subString()方法

package com.xyq.demo;

public class Reverse {
	public static void main(String[] args) {
		String s = "残花百力无风东,难亦别难时见相";
		int len = s.length();
		String reverse = "";
		for (int i = len; i > 0; i--)
			reverse += s.substring(i - 1, i);
		System.out.print(reverse);
	}
}

 输出:相见时难别亦难,东风无力百花残

 

2.StringBuffer的reverse()方法

package com.xyq.demo;

import java.util.Scanner;

public class Reverse {
	public static void main(String[] args) {
		String str;
		System.out.println("请输入:");
		Scanner scan=new Scanner(System.in);
		str=scan.nextLine();
		str=(new StringBuffer(str).reverse()).toString();
		System.out.println(str);
	}
}

 请输入:

123

321

 

3.禁止使用String,StringBuffer,Integer  (整数逆序打印)

package com.xyq.demo;


public class Reverse {
	public static void main(String[] args) {
		output(103658);
	}

	public static void output(int num) {
		int temp = 0;
		while (num > 9) {
			temp = num % 10;
			System.out.print(temp);
			num = (int) (num / 10);
		}
		System.out.print(num);
	}
}

 输出:856301

 

4.栈

package com.xyq.demo;

import java.util.Stack;

public class Reverse {
	public static void main(String[] args) {
		reverseStr("103658");
	}
	@SuppressWarnings("unchecked")
	public static void reverseStr(String s) {
		Stack myStack = new Stack();
		for (int i = 0; i <= s.length() - 1; i++) {
			myStack.push(String.valueOf(s.charAt(i)));
		}
		while (!myStack.empty()) {
			System.out.print((String) myStack.pop());
		}
	}
}

 输出:856301

 

5.数组

package com.xyq.demo;

public class Reverse {
	public static void main(String[] args) {
		System.out.println(f("103658"));
	}

	public static String f(String s) {
		char[] c = s.toCharArray();
		char[] temp = new char[c.length];
		for (int i = 0, j = c.length - 1; i < c.length; i++, j--) {
			temp[j] = c[i];
		}
		return new String(temp, 0, temp.length);
	}
}

 输出:856301

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics