2016/10/06 联想模拟测试的一道小小编程题
来源:互联网 发布:电线传输数据 编辑:程序博客网 时间:2024/05/17 00:06
判断回文数。这个编程题目大家可能都已经做烂了,但是今天在做联想的模拟测试的时候,还是出了一些小问题。所以提出来,记录一下。
#include<iostream>using namespace std;bool isPalindrome(int x){ int tmp = x; int i; int tmp1,tmp2; int *hd; int* p; int cnt = 1; bool flg = true; cout<<"the num is "<<x<<"\t"<<endl; while(x/10 >= 1) { cnt = cnt +1; x = x / 10; } cout<<"length of x is "<<cnt<<" \t"<<endl; x = tmp; hd = (int*)malloc(sizeof(int) * cnt); p = hd; while(x/10 >= 1) { *p = x%10; x = x / 10; //p = p + sizeof(int); p = p + 1; } *p = x; p = hd; for(i = 0;i <= (cnt / 2);i++) { tmp1 = *(p + i*1); tmp2 = *(p + (cnt - i - 1) * 1); //tmp1 = *(p + i * sizeof(int)); //tmp2 = *(p + (cnt - i - 1) * sizeof(int)); cout<<tmp1<<" and "<<tmp2<<endl; if( tmp1 != tmp2) { flg = false; return flg; } } return flg;}void main(void){ int x; cin>>x; while(x < 0) { cout<<"input must larger than or equal to 0"<<endl; cin>>x; } bool flg = isPalindrome(x); cout<<flg<<endl; system("pause");}
重点在于被屏蔽的一行,原来没有注意到,动态申请的连续内存单元在指针后移的时候只需要 p = p + 1;
即可实现后移到下一个申请的内存单元,从第一个 int
单元移动到下一个int
单元 ,从一个double
单元移动到下一个double
单元,而不用像被屏蔽的那个那样p = p + sizeof(int);
。
在另一个方面,我也决定看看C++里面的vector,比这C语言里面的好使多了!
下面是10月7日通过vector实现的程序,的确是要精简很多了,少了一次循环
#include<iostream>#include<vector>using namespace std;bool isPalindrome(int x){ vector<int> eve; int i; cout<<"input num is "<<x<<endl; while(x/10 >= 1) { eve.push_back(x % 10); x = x / 10; } eve.push_back(x); int len = eve.size(); for(i = 0;i <= (len /2);i++) { int tmp1 = eve.at(i); int tmp2 = eve.at(len - i - 1); cout<<tmp1<<" and "<<tmp2<<endl; if(tmp1 != tmp2) { return false; } } return true;}void main(void){ int x; cin>>x; while(x<0) { cout<<"input must larger than or equal to 0!"<<endl; cin>>x; } cout<<isPalindrome(x)<<endl; system("pause");}
0 0
- 2016/10/06 联想模拟测试的一道小小编程题
- 小小的测试题
- 一道小小的智力题
- 从一道概率题联想到的logistic 回归
- dom4j 的小小测试
- 测试的小小收获
- 一道小小的内存申请面试题
- 一道SQL的面试题之联想
- 一道SQL的面试题之联想
- 一道多线程笔试题目的联想
- hdu 5402 一道神奇的模拟题
- 一道很小的编程题
- 一道printf的编程题
- 一道有趣的编程题
- 360的一道编程题
- 一道简单的编程题
- 一道渡口模拟题
- EMC的一道数字编程编程题
- springMVC和数据库中的一些乱码问题
- js按钮全选反选
- String StringBuffer StringBuilder
- RTSP 流程
- hdu 1195 Open the Lock(BFS)
- 2016/10/06 联想模拟测试的一道小小编程题
- 有关内存泄漏的分析
- 编译原理———文法
- RTSP 详细消息交互
- AsyncTask研究
- Mycat源码篇 : 起步,Mycat源码阅读调试环境搭建
- if else 应用之经典例题判断能否构成三角形并输出面积
- Android RecyclerView点击事件与长按事件
- 【微信开发】-发送位置进行普通IP定位,主要代码在private function receiveLocation($object)