Amazon Interview Question
Software Engineer / DevelopersCountry: United States
(1)if size < 1000, unit is B
(2)if 1000 <= size < 10,000, result as "*.**K" is most accurate
(3)if 10,000 <= size < 100,000, result as "**.*K" is most accurate
(4)if 100,000 <= size < 1000,000, result as "***K" is most accurate
(5)if 1,000,000 <= size < 10,000,000, result as "*.**M" is most accurate
(6)if 10,000,000 <= size < 100,000,000, result as "**.*M" is most accurate
(7)if 100,000,000 <= size < 1000,000,000, result as "***M" is most accurate
(8)if size == 1000,000,000, result is "1G"
Code in C++:
string formatFileSize(unsigned int size)
{
char s[8] = {0};
if(size < 1000){
sprintf(s, "%uB", size);
return string(s);
}
else if(size < 10000) sprintf(s, "%.2fK", size * 1.0);
else if(size < 100000) sprintf(s, "%.1fK", size * 1.0);
else if(size < 1000000){
sprintf(s, "%uK", (size - size % 1000)/1000);
return string(s);
}
else if(size < 10000000) sprintf(s, "%.2fM", size * 1.0);
else if(size < 100000000) sprintf(s, "%.1fM", size * 1.0);
else if(size < 1000000000){
sprintf(s, "%uM", (size - size % 1000000)/1000000);
return string(s);
}
else return string("1G");
return removeTailingDecimalZeros(string(s));
}
string removeTailingDecimalZeros(const string& num)
{
size_t i = num.find('.'), j = num.size() - 1;
if(i == string::npos) return num;//an integer without decimal point
for(; j > i; --j){
if(num[j] != '0') break;
}
if(j == i) ++j;//if num is 37.0000, the result will be 37.0
return num.substr(0, j+1);
}
void formatsize(int size)
{
int dig=0;
int pow=1;
int num=size;
while(num>0)
{
num=num/10;
dig++;
pow=pow*10;
}
num=size%pow;
size=num;
dig=0;
pow=1;
while(num>0)
{
num=num/10;
dig++;
pow=pow*10;
}
num=size;
if(dig<=3)
{
printf("%dB\n",num);
return;
}
pow=pow/100;
if(pow<=1000)
pow=1000;
else if (pow<=1000000)
pow=1000000;
double n=(double)size/pow;
if(pow==1000)
printf("%.1fK\n",n);
else if(pow==1000000)
printf("%.1fM\n",n);
}
std::string convert_integer(int integer)
{
char a[4]={'B','K','M','G'};
int level=0;
double val=(double)integer;
int limit=1000;
while(val>=limit)
{
level++;
val=val/1000.0;
}
std::stringstream stream1;
stream1<<std::setprecision(3)<<val<<a[level];
return stream1.str();
}
int main()
{
int integer=10001;
std::cout<<convert_integer(integer)<<"\n";
return 0;
}
public static String formatFileSize(long size) {
- Anonymous April 02, 2014String hrSize = null;
double b = size;
double k = size/1024.0;
double m = ((size/1024.0)/1024.0);
double g = (((size/1024.0)/1024.0)/1024.0);
double t = ((((size/1024.0)/1024.0)/1024.0)/1024.0);
DecimalFormat dec = new DecimalFormat("0.00");
if ( t>1 ) {
hrSize = dec.format(t).concat(" TB");
} else if ( g>1 ) {
hrSize = dec.format(g).concat(" GB");
} else if ( m>1 ) {
hrSize = dec.format(m).concat(" MB");
} else if ( k>1 ) {
hrSize = dec.format(k).concat(" KB");
} else {
hrSize = dec.format(b).concat(" Bytes");
}
return hrSize;
}