Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
这种数还有一个特点点,旋转后与原来是一样的。 循环取模10的余数,由余数重新构造一个数,与原来的数相比
send by my HTC G12 .
--
您收到此邮件是因为您订阅了 Google 网上论坛的“Shenzhen (深圳) Linux Unix User Group”论坛。
要退订此论坛并停止接收此论坛的电子邮件,请发送电子邮件到 szlug+un...@googlegroups.com。
要查看更多选项,请访问 https://groups.google.com/groups/opt_out。
这个算法并不需要strrev,不需要任何拷贝操作,只要判断1和n,2和n-1...直到n/2就可以,不必考虑奇偶。
回文数判定转成字符串是高效简洁的方法,使用动态类型的语言来做的话,一个非常大的整数(超过20位)只要0.007秒,可以看做是个足够好的方法
--
--
You received this message because you are subscribed to the Google
Groups "Shenzhen DIY community" group.
To post to this group, send email to sz...@googlegroups.com
To unsubscribe from this group, send email to
szdiy+un...@googlegroups.com
For more options, visit this group at
http://www.szdiy.org
http://groups.google.com/group/szdiy?hl=zh-CN
---
您收到此邮件是因为您订阅了 Google 网上论坛的“Shenzhen DIY community”论坛。
要退订此论坛并停止接收此论坛的电子邮件,请发送电子邮件到 szdiy+un...@googlegroups.com。
要查看更多选项,请访问 https://groups.google.com/groups/opt_out。
> ����˼���ܿ죬google ���Ҵ��� http://www8.cs.umu.se/~isak/snippets/ ��� strrev.c
>
> char *strrev(char *str)
> {
> char *p1, *p2;
>
> if (! str || ! *str)
> return str;
> for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
> {
> *p1 ^= *p2;
> *p2 ^= *p1;
> *p1 ^= *p2;
���Dz����м�temp������ ��������������ֵ��
Search for "swap variables without temp"
http://en.wikipedia.org/wiki/XOR_swap_algorithm
http://betterexplained.com/articles/swap-two-variables-using-xor/
Would you really use this?
No way. This is a cool trick, but don��t write this as an actual swap function.
1 bool helper(int x, int d) { 2 if (x<10) return true; 3 if (x%10 != x/d) return false; 4 5 x /= d; 6 d /= 10; 7 return helper(x%d, d/10); 8 } 9 bool isPalindrome(int x) { 10 int d; 11 for (d=1; x/d>9; d*=10); 12 return x>=0 && helper(x, d); 13 }
自然,面试没有通过(因为我的 C 语言基础知识学得并不扎实,又很长一段时间都没有写代码了,再加上面试前未作准备)。
--
你这中写法不一定对了来着,这种写法c标准完全没有规定执行顺序,看编译器的,而且应该是不安全的写法,原来就是用异或运算来做的,x^x^y=y 的原理 简单来说就是与自己异或为0
#风起看云涌,叶落品人生#
On Mon, 2013-07-29 at 16:06 +0800, Ashi wrote:一般这个用法不会使用函数,而是用宏,一旦你用了指针hold住变量,最后编译器
> 我觉得可以从数据依赖性上分析这两个算法的性能问题,正常方法没有Read after
> Write(RAW)型[0]的数据依赖,而异或写法有RAW数据依赖。因RAW会导致CPU流水线利用率下降,也就是指令级并行减少([1]中也提到了),因此执行效率会低。
>
> 附上我的测试代码,下面是我在x86的平台上用gcc-4.7.2 -O2 -lrt选项的结果:
> 10000000 normal swap cost: 18171
> 10000000 inplace swap cost: 46266
> 异或写法要慢2.5倍左右。
>
(至少GCC会这样)就不得不使用间接寻址(RAW的问题就来了),而你如果用宏的
话,编译器可以利用标量演化(scalar evolution)将数值处理成立即数,同时也没
有RAW的问题(因为是xor相当于half-xchg then mov,算是原子操作).注意这个
跟宏展开的提速没有关系,如果用指针,即便你用inline,优化效果几乎没有,因
为只展开了一次。测试结果一目了然:
--------------------result--------------------
10000000 normal swap cost: 20184
10000000 inplace swap cost: 48538
10000000 new swap cost: 9764
---------------------end-----------------------
不过代码就没法用函数指针来写通用的测试函数了,测试函数要重写
PS: 贴出这个测试结果希望不要让同学们误会,这不过是一个讨论贴,千万千万*
不要*在你的生产代码里玩这个奇技淫巧!