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
| package com.code.note.test;
public class Solution {
public Double parseDouble(String n) {
int isNegative = 1;
String numStr = n.trim(); if (numStr == null) return 0D; if (numStr.length() > 0 && numStr.charAt(0) == '-') { isNegative = -1; numStr = numStr.substring(1); } else if (numStr.charAt(0) == '+') { numStr = numStr.substring(1); }
if (!numStr.contains(".")) { return (double) getHighPosNum(n); }
String[] arr = numStr.split("\\.");
double sumHigh = getHighPosNum(arr[0]);
double sumLow = getLowPosNum(arr[1]);
return isNegative * (sumLow + sumHigh); }
private long getHighPosNum(String highStr1) { long sumHigh = 0; String highStr = highStr1; char[] highChars = highStr.toCharArray(); int[] highIntNums = new int[highChars.length];
for (int i = 0; i < highIntNums.length; i++) { sumHigh += Math.pow(10, highIntNums.length - 1 - i) * isDigit(highChars[i]); } return sumHigh; }
private int isDigit(char highChar) { if (!Character.isDigit(highChar)) { throw new NumberFormatException("非法数字"); } return (int) highChar - (int) '0'; }
private double getLowPosNum(String lowStr1) { double sumLow = 0D; String lowStr = lowStr1; char[] lowChars = lowStr.toCharArray(); int[] lowIntNums = new int[lowChars.length];
for (int i = 0; i < lowIntNums.length; i++) { sumLow += Math.pow(10, -1 * (i + 1)) * (isDigit(lowChars[i])); } return sumLow; }
public static void main(String[] args) {
Solution s = new Solution(); double a = s.parseDouble("-1.456"); System.out.println(a); } }
|