2014-05-21 4 views
2

바이트 수를 나타내는 정수를 예쁜 형식으로 변환하는 알고리즘입니다. 최대 3 자리 (십진수는 포함되지 않음) - 예 : Linux 명령 줄과 같은 경우. 더 선행 또는 후행 제로 1K는 1000 바이트예쁜 숫자 형식 알고리즘

내가 무슨 짓을했는지 알고 싶습니다
Examples: 
Correct 
123B -> 123B 
12300B -> 12.3K 
1910000B -> 1.91M 
1000000000B -> 1G 
83123 = 83.1K (not 83K) 

Incorrect 
012K (should be 12K) 
8.20M (should be 8.2M) 

없는 내가 잘못 할 또는이 문제를 해결하는 쉬운 더 나은 방법이 또는 내 코드에 버그가있는 경우.

아래는 내 솔루션입니다 (그래서 내가 뭘 잘못했는지의 생각을하지 않은 그것은 작동하지만 내가 선택하지 않은) -

/* 
    * @Description - Function takes integer as input and returns the number in 
    * pretty format(Gigabyte, Megabytes, KiloBytes, Bytes) with maximum of 3 
    * digits 
    * @param integer to convert to pretty format 
    * @Assumptions - As mentioned in the problem set, 1000bytes = 1KB 
    * Value is rounded to the nearest valid value 
    * In java leading 0 in number is considered Octal, this function does not 
    * take care of octal to decimal conversion 
    * As 1G = 1,000,000,000B the loop will run maximum 3 times in worst case 
    * Its requires constant space O(1) to store the result 
    */ 
    static String fpretty(int num) { 

    int count = 0; 
    double div_result = (double) num; 
    String display = ""; 

    /* 
    * Every time we divide by 1000 count is incremented from B->K->M->G 
    * Here two decimal places are preserved for cases like 1.05, 1.11 
    * The output result of this loop will have 1,2 or 3 digits with max 
    * two decimal places 
    */ 
    while(div_result > 999.5) { 
     div_result = div_result/1000; 
     div_result = Math.round(div_result * 100.0)/100.0; 
     count++; 
    } 

    // Get suffix B, K, M or G 
    String measure = getUnit(count); 

    // If decimal places is all zeros OR result has 3 digits 
    if(div_result % 1 == 0 || div_result >= 100) 
     display = (int)div_result + measure; 
    // If result has 2 digits 
    else if (div_result >= 10) { 
     // Then fetch 1 decimal place as we have 2 digits 
     div_result = (Math.round(div_result * 10.0)/10.0); 
     // If after rounding decimal places are .0 then truncate zeros 
     // eg. 99.97 rounded to -> 100.0 -> 100 
     if(div_result % 1 == 0) 
     display = (int)div_result + measure; 
     else 
     display = div_result + measure; 
    } 
    else 
     display = div_result + measure; 

    return display; 
    } 
+0

당신이 "꽤 형식" – NathanTempelman

+0

무엇을 의미하는 나는 꽤 형식은 사람이 읽을 수있는 형식을 호출 -h' 무엇을 'LS입니다 완전히 명확하지 않다 생각하는 것 : 그것은 "1.2M"또는 같은 값으로 파일 크기를 단축 23.9k "입니다. 그러나 코드가 잘못된 부분을 볼 수는 없습니다. –

+0

예를 추가했습니다. – NitishMD

답변

4

이것은 DecimalFormat 클래스를 사용하여 훨씬 적은 노력으로 수행 할 수 있습니다. 패턴을 사용하여 설명 할 수 있고 반올림 방법을 RoundingMode으로 선택할 수있는 반올림을 수행하십시오. 또한 무시되는 0으로 끝나는 0을 처리합니다.

public String pretty(int num) { 
    DecimalFormat f = new DecimalFormat("###.##"); 
    f.setRoundingMode(RoundingMode.HALF_UP); 
    double prettyd = num; 
    int count = 0; 
    while (prettyd >= 1000.0) { 
     prettyd /= 1000.0; 
     count++; 
    } 
    return f.format(prettyd) + getUnit(count); 
} 
+0

감사합니다. 우아합니다. inbuilt 함수를 사용할 수 없으면 어떻게 해결할 수 있습니까? – NitishMD

+0

@NitishMD 이상한 제약 조건입니다. inbuilt 함수는 무엇입니까? Math 라이브러리 String.format(), BigDecimal ...? –