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

二.编程题
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;
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值