바이트 수를 나타내는 정수를 예쁜 형식으로 변환하는 알고리즘입니다. 최대 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;
}
당신이 "꽤 형식" – NathanTempelman
무엇을 의미하는 나는 꽤 형식은 사람이 읽을 수있는 형식을 호출 -h' 무엇을 'LS입니다 완전히 명확하지 않다 생각하는 것 : 그것은 "1.2M"또는 같은 값으로 파일 크기를 단축 23.9k "입니다. 그러나 코드가 잘못된 부분을 볼 수는 없습니다. –
예를 추가했습니다. – NitishMD