w****f 发帖数: 684 | 1 今天的一个电面, Implement itoa() with C++ and give test cases!
string intToStr(int n)
{
bool isNeg =false;
if(n<0) {
isNeg =true;
n *= -1;
}
string str;
do {
str += (char) ( n%10 + "0");
n /=10;
} while(n>0);
if(isNeg) str += "-";
int nstr=str.size();
for( int i=0; i
string ct = str[i];
str[i] = str[ nstr-1 -i];
str[nstr-1-i] =ct;
}
return str;
}
test cases: 123, -123, 0, 1, 123456789
可interviewer 说我漏了一种test case, will fail for a extreme rare case。。
。
一个近说 extreme rare,not important。。。
谁知道是哪种case? |
M*****s 发帖数: 203 | 2 INT_MIN, overflow了吧
【在 w****f 的大作中提到】 : 今天的一个电面, Implement itoa() with C++ and give test cases! : string intToStr(int n) : { : bool isNeg =false; : if(n<0) { : isNeg =true; : n *= -1; : } : string str; : do {
|
B*******1 发帖数: 2454 | |
w****f 发帖数: 684 | 4 yaaaaaaa..........
当时怎么也没想起来! 可是怎么fix呢? |
w****f 发帖数: 684 | 5 yaaaaaaa..........
当时怎么也没想起来! 可是怎么fix呢? |
w****f 发帖数: 684 | |
s***0 发帖数: 117 | 7 : string strToInt(int n)
Wrong function name: int to str.
Pretend your system is 8 bits: you have 8 bit 2's complement
pass in n = -128, your function now has n = 128. but the biggest 2's
complement # is 127. I'm not sure what happens here off the top of my head.
bitwise arithmetic would have been a better way to approach this. |
w****f 发帖数: 684 | 8
Good catch!
.
Do you know how to implement it use "bitwise arithmetic"?
【在 s***0 的大作中提到】 : : string strToInt(int n) : Wrong function name: int to str. : Pretend your system is 8 bits: you have 8 bit 2's complement : pass in n = -128, your function now has n = 128. but the biggest 2's : complement # is 127. I'm not sure what happens here off the top of my head. : bitwise arithmetic would have been a better way to approach this.
|
w****f 发帖数: 684 | 9 find one solution to fix INT_MIN problem
string intToStr(int n)
{
bool isNeg=false;
if(n<0) isNeg=true;
string str;
do {
str += (char) ( abs(n%10) + '0');
n /=10;
} while(n>0);
if(isNeg) str += '-';
int nstr=str.size();
for( int i=0; i
string ct = str[i];
str[i] = str[ nstr-1 -i];
str[nstr-1-i] =ct;
}
return str;
} |
p***e 发帖数: 69 | 10 你这样n为负的时候只做了一次。。。。。
你的意思是这样吧?
do {
...
...
} while(abs(n) > 0)
【在 w****f 的大作中提到】 : find one solution to fix INT_MIN problem : string intToStr(int n) : { : bool isNeg=false; : if(n<0) isNeg=true; : string str; : do { : str += (char) ( abs(n%10) + '0'); : n /=10; : } while(n>0);
|
d******0 发帖数: 191 | |