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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值