您的位置:首页 > 编程语言

京东2015年应届生招聘笔试题(A)卷答案编程题和附加题部分

2014-10-12 21:25 375 查看
二.编程题

1.题目大意:编写一个函数func(int n),使得返回值是最小的各位乘积等于n的数,且返回值至少两位数。(题目有点看不太清,我就按这样理解了。如果和题目有出入稍微修改一下应该就能解决。)

C++代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int func(int n) {
int ans = 0 , t = 1;
for(int i=9;i>1;i--) {
while(n % i == 0) {
n /= i;
ans = ans + t * i;
t *= 10;
}
}
if(n != 1) return -1;
if(ans == 0) ans = 1;
if(ans < 10) ans += 10;
return ans;
}
int main() {
int n;
while(scanf("%d" , &n) != EOF) {
int ans = func(n);
cout << ans << endl;
}
return 0;
}


2.使用非递归方式实现二叉树的先序遍历,并将节点的值保存在数组中。

C++函数原型:

struct TreeNode {

int value;

TreeNode* left;

TreeNode* right;

};

void TraverseTreeInPreOrder(std:vector<int>&value,const TreeNode* root) {

}

思路:最基础的搜索按照某一种方式来分可以分为深度优先搜索和广度优先搜索,深度优先搜索使用栈,或者说递归;广度优先搜索使用队列。这里要求非递归,则采用队列。

C++代码(未实现,C++基础不是太好,不过程序能够体现算法细节,仅作参考):

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vecotr>
#include <queue>
using namespace std;
struct TreeNode {
int value;
TreeNode* left;
TreeNode* right;
};
void TraverseTreeInPreOrder(std:vector<int>&value,const TreeNode* root) {
TreeNode*u ;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
u = que.front();
que.pop();
value.push(u->value);
if(u->left != null) que.push(u->left);
if(i->right != null) que.push(u->right);
}
}


附加题:写出第k个素因子只有2、3、5的数。

因为数的个数相对较少,所以可以初始化。

C++代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10000001;//假设数的范围不会超过1000万
int a[1010] , cnt = 0;
bool vis[maxn];
void dfs(int x) {
if(x >= maxn || vis[x]) return;
vis[x] = true;
a[cnt++] = x;
dfs(x*2);
dfs(x*3);
dfs(x*5);
}
int KthNumber(int k) {
return a[k-1];
}
int main() {
dfs(1);
sort(a , a+cnt);
int k;
while(scanf("%d" , &k) != EOF) {
int ans = KthNumber(k);
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: