1. 使用现成的 reverse() 方法
StringBuilder sb1 = new StringBuilder("Hello you"); System.out.println(sb1.reverse()); //uoy olleH StringBuffer sb2 = new StringBuffer("haha go"); System.out.println(sb2.reverse()); //og ahah
2. 将字符串转换成字符数组,然后从末尾开始,拼接字符串
void re(String str){ char[] charStr = str.toCharArray(); StringBuilder sb = new StringBuilder(); for (int i = charStr.length - 1; i >= 0; i--) { sb.append(charStr[i]); } System.out.println(sb); }
3. 对于整数,一种是可以转换成字符串,另外也可以通过取余和除直接倒置
void re(int num){ int res = 0; while(num > 0){ res = res * 10 + num % 10; num /= 10; } System.out.println(res); }
void re(int num){ int res = 0; while(num > 0){ // System.out.println("num is " + num); res = res * 10 + num % 10; num /= 10; } System.out.println(res);}
原文地址:https://www.cnblogs.com/ainsliaea/p/10521910.html
时间: 2024-10-08 01:52:44