----------------此题来源于我的期末考试历年真题一直苦于没有学长整理答案,希望黑马会做的同学帮写下答案或纠正我的解法方便我整理答案备考---------------
题目:输入正整数,把第i位和第i+1位互换,比如1234,变成2143,12345变成103254(当输入的整数为奇数时,在第一位补0变成偶数位,然后将第2i-1位与第2i位互换)
解答:Exchange.java
- import java.util.Scanner;
- class Exchange
- {
- public static void main(String args[])
- {
- Scanner scanner = new Scanner(System.in);
- System.out.println("请输入一个整数");
- String str = scanner.next();
- System.out.println("你所输入的整数为"+str);
- String stri;
- //System.out.println(str.length()/2);
- if((str.length()%2)==0)
- stri = str;
- else
- stri = "0"+str;
- char[] ch = stri.toCharArray();
- for(int i=0;i<ch.length/2;i++)
- {
- int a = 2*i;
- int b = 2*i+1;
- swap(ch,a,b);
- }
- StringBuffer sb = new StringBuffer();
- for(int i = 0; i < ch.length; i++){
- sb.append(ch[i]);
- }
- String newStr = sb.toString();
- System.out.println("第i位和第i+1位调换后的整数位为:"+newStr);
- }
- public static void swap(char[] ch,int x,int y)
- {
- char temp = ch[x];
- ch[x]=ch[y];
- ch[y]=temp;
- }
- }
复制代码
运行:
|