【洛谷OJ】【JAVA】P1553 数字反转(升级版)

xiaoxiao2021-03-01  10

这个题比较坑,要注意的是

(1)0.0或00.00最后应该是0.0

(2) 0/0或00/00最后应该是0/0

import java.util.Scanner; public class Main { private static Scanner cin; public static void main(String args[]) throws Exception { cin = new Scanner(System.in); String word = cin.nextLine().trim(); StringBuffer ret = new StringBuffer(); if (word.contains(".")) { String[] decimal = word.split("\\."); ret.append(removeStartZero(revertString(removeStartZero(decimal[0]), true))); ret.append("."); ret.append(removeEndZero(revertString(removeEndZero(decimal[1]), false))); } else if (word.contains("/")) { String[] decimal = word.split("/"); ret.append(removeStartZero(revertString(removeStartZero(decimal[0]), true))); ret.append("/"); ret.append(removeStartZero(revertString(removeStartZero(decimal[1]), false))); } else if (word.contains("%")) { ret.append(removeStartZero(revertString(removeStartZero(word.substring(0, word.length() - 1)), true))); ret.append("%"); } else { ret.append(removeStartZero(revertString(removeStartZero(word), true))); } System.out.println(ret.toString()); } private static String removeEndZero(String value) { int index = -1; StringBuffer sb = new StringBuffer(); for (int i = value.length() - 1; i > 0; i--) { if (value.charAt(i) == '0') { index = i; } else { break; } } if (0 < index) { sb = new StringBuffer(value.substring(0, index)); } else if (0 == index) { // let the sb empty } else { sb = new StringBuffer(value); } return sb.toString(); } private static String removeStartZero(String value) { int index = -1; StringBuffer sb = new StringBuffer(); for (int i = 0; i < value.length(); i++) { if (value.charAt(i) == '0') { index = i; } else { break; } } if ((value.length() == 1 && 0 == index) || (value.length() == index + 1)) { sb = new StringBuffer("0"); } else if (-1 != index) { sb = new StringBuffer(value.substring(index + 1, value.length())); } else { sb = new StringBuffer(value); } return sb.toString(); } private static String revertString(String value, boolean removezero) { StringBuffer sb = null; sb = new StringBuffer(value); sb.reverse(); return sb.toString(); } }

 

转载请注明原文地址: https://www.6miu.com/read-3850329.html

最新回复(0)