Question
My thought
Nothing… The problem is pretty easy, however it troubled me for a quite long time. Just follow the instruction of the problem and simulate the whole process by coding.
Points to note
The conversion between String
and int
How to handle carry
Pay attention to the additional sign
Sometimes we can use char
to simplify the process
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 import java.util.Scanner;class test { static String num1; static int num2,num3; public static void input () { Scanner input = new Scanner (System.in); String s = input.next(); int len = s.length(); for (int i=0 ;i<len;i++) { if (s.charAt(i)==',' ) { num1 = s.substring(0 ,i); num2 = s.charAt(i+1 )-'0' ; num3 = s.charAt(i+3 )-'0' ; break ; } } input.close(); } public static void noSolution (int decimalPoint) { int IntgerNum = num2 - num3 - 1 ; while ((IntgerNum--)!=0 ) { System.out.print("#" ); } System.out.print("." ); for (int i=0 ;i<num3;i++) { System.out.print("#" ); } } public static void process () { int decimalPoint = num1.indexOf("." ); int decimalLength = num1.length() - decimalPoint - 1 ; int integerLength = decimalPoint; if (decimalLength < num3 ||integerLength + 1 + num3 > num2) { noSolution(decimalPoint); return ; } String newNum = num1.substring(0 ,decimalPoint+num3+1 ); String tmp="" ; int newLen = newNum.length(); for (int i=0 ;i<newLen;i++) { if (newNum.charAt(i)=='.' ) continue ; tmp += newNum.substring(i,i+1 ); } int haveASign = 0 ; if (tmp.charAt(0 )=='+' ) { haveASign = 1 ; tmp = tmp.substring(1 ); } else if (tmp.charAt(0 )=='-' ) { haveASign = -1 ; tmp = tmp.substring(1 ); } int intTmp = Integer.valueOf(tmp); if (newLen+1 <=num1.length() && num1.charAt(newLen)>'4' ) intTmp++; String stringTmp = Integer.toString(intTmp); int nowLength = stringTmp.length() + 1 + Math.abs(haveASign); int cntOutput = 0 ; for (int i=0 ;i<num2-nowLength;i++) { System.out.print("#" ); cntOutput++; } if (haveASign==-1 ) { System.out.print("-" ); cntOutput++; } else if (haveASign==1 ) { System.out.print("+" ); cntOutput++; } int p=0 ; for (p=0 ;p<num2-1 -cntOutput-num3;p++) { System.out.print(stringTmp.charAt(p)); } System.out.print("." ); for (;p<stringTmp.length();p++) { System.out.print(stringTmp.charAt(p)); } } public static void main (String[] args) { input(); process(); } }
Tips
String.split(String)
This method can be used to split a string into parts following the instruction.
When use .
or |
as the symbol of split position, we need to use Escapes //
.
It returns a array with the satisfied arrays