You are right, I omitted the overflow condition in the code, and it can be workarounded as follow: int get_max(int a,int b) { long long divisor = (long long)a-(long long)b; int array[2]; array[0]=a; array[1]=b; return array[( divisor & (ULLONG_MAX/2+1U) ) >> ((sizeof(long long)*8)-1)]; }
As far as I am concerned, this question is rather an excersice than what will be used in the real engineering environment. It forces the coder to implement an "if(a<b){....}" expression with high level programming language C rather than the compiler generated assembly. In the assembly we can get the value of the status-register, which will help us know the overflow in the last caculation. but with pure C it is hard to get this valuable information(if I am wrong please correct me).So it's impossible to implement a perfect "if(a<b){...}" without knowing the processor details. And it's impossible for a program caring the processor details be portable! If we see the question as an excersice for "if(a<b){....}" and an interesting puzzle, it is worthwhile to have a try and have some fun. The "if(a>b){return a;}..." like impl is surely not stupid for the real-world engineering, but it is surely not a clever answer for a puzzle, right? Anyway, I am with this answer just because that I am with this sounds-interesting-question, not means that I support this kind of coding standard in the project. I take your point that in engineering practice, simply is the best. BTW, is there any perfect solution to implement the "if(a<b){....}" without any Relational Operator? -----邮件原件----- 发件人: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] 发送时间: 2007年12月8日 22:47 收件人: [EMAIL PROTECTED] 抄送: [EMAIL PROTECTED] 主题: Re: greatest of two numbers On Dec 8, 9:35 am, James Fang <[EMAIL PROTECTED]> wrote: > Thanks for your correction... > > int get_max(int a,int b) > { > int array[2]; > array[0]=a; > array[1]=b; > return array[( (a-b)& (UINT_MAX/2+1U) ) >> > ((sizeof(int)*8)-1)];} > > int main() > { > printf("%d\n",get_max(-190,-100)); > printf("%d\n",get_max(10000,100)); > printf("%d\n",get_max(99,199)); > > } Still wrong. With your code, printf("%d \n",get_max(2147483647,-1)); will print -1 as the answer. Your entire attempt is stupid, and the OP's requirement is stupid. Your whole attempt is pointless, and encourages stupid programming. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to algogeeks@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/algogeeks -~----------~----~----~----~------~----~------~--~---