盛大18秋招java开发编程题一道

在牛客网获得了许多的帮助,也希望我的帖子可以给别人到来一些帮助吧

找出最接近的对称数字

输入一个正整数的字符串,输出与它最接近的对称数字(不包括它自己)的字符串

1: 输入字符串的长度最多不会超过18

2: 当大于输入数字和小于输入数字的对称数字与输入数字距离相同时,取小的数字作为答案

输入

输入为一个正整数的字符串

输出

输出为与输入数字最接近的对称数字(不包括输入本身)的字符串

样例输入

"123"

样例输出

"121"



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

#include <iostream>

#include <vector>

#include <numeric>

#include <limits>

#include <math.h>

using namespace std;

bool isNotaba(string n) {

int sz = n.size();

for (int i = sz / 2; i >= 0; i--) {

if (n[i] != n[sz - i - 1])

return true;

}

return false;

}

string min(string a, string b, string n) {

long long low, high, com;

sscanf(a.c_str(), "%lld", &low);

sscanf(b.c_str(), "%lld", &high);

sscanf(n.c_str(), "%lld", &com);

long long d1 = llabs(low - com), d2 = llabs(high - com);

if(d1 == d2) {

if(low <= high) return a;

else return b;

} else if (d1 > d2) {

return b;

} else {

return a;

}

return NULL;

}

string find(string n, bool higher) {

//tow special case: 9 and 11

if(n == "9") {

if(higher) return "11";

}

if(n == "11") {

if(!higher)  return "9";

}

int sz = n.length();

long long prevHalf;

sscanf(n.substr(0, (sz + 1) / 2).c_str(), "%lld", &prevHalf);

//    cout << "prev half is " << prevHalf << endl;

if (higher)

prevHalf++;

else

prevHalf--;

char ph[10];

snprintf(ph, 10, "%lld", prevHalf);

//    cout << "ph is " << ph << endl;

int ph_len = strlen(ph);

//    cout << "sz=" << sz << ",ph_len=" << ph_len << endl;

int d = (sz + 1) / 2 - ph_len; //产生进位或者退位

int s = 0;

char b = '9';

char fill_char = '#';

if (d < 0) {

s = sz + 1;

} else if (d > 0) {

s = sz - 1;

} else if (sz & 0x1) {

s = 2 * ph_len - 1;

} else {

s = 2 * ph_len;

}

//    cout << "s= " << s << endl;

string res(s, fill_char);

//    cout<<"res="<<res<<endl;

for (int i = 0; i < s; i++) {

if (i < ph_len)

res[i] = ph[i];

else

res[i] = res[s - 1 - i];

}

if(res[ph_len] == fill_char) {

res[ph_len] = b;

}

return res;

}

string NearestNum(string n) {

if (n.size() == 0)

return NULL;

if (isNotaba(n)) {

int sz = n.length();

for (int i = sz / 2; i < sz; i++) {

n[i] = n[sz - 1 - i];

}

} else {

string low, high;

low = find(n, false);

high = find(n, true);

//        cout << "low=" << low << ",high=" << high << endl;

n = min(low, high, n);

}

return n;

}

int main() {

string res;

string _n;

getline(cin, _n);

res = NearestNum(_n);

cout << res << endl;

return 0;

}


#秋招##盛趣##笔试题目##Java工程师#
全部评论
面试有点难
点赞 回复
分享
发布于 2019-01-16 20:50

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务