[面经]CVTE技术二面一道算法题

题目描述: 1+11+111+…+1111111111=sum,最后一个二进制数是n个1。计算二进制数的累加后sum的值。
思路解析:

  1. 首先,这明显是个大数问题。所以建议所有数都用字符串来表示或者是int数组来表示。这里我们用字符串来表示。
  2. 使用字符串表示二进制数的话,需要实现两个二进制数字符串形式的加法运算。(关键)
  3. 需要有制造这么多个1的字符串数组的方法。
  4. 使用循环迭代的方式将二进制数组累加起来。

我们从最简单的方法写起吧,先从”大数制造器”开始。

1
2
3
4
5
6
7
8
9
10
public static String[] createNums(int n){
if(n<=0) return null;
StringBuilder sb=new StringBuilder();
String[] nums = new String[n];
for(int i=0;i<n;i++){
sb.append(1);
nums[i]=sb.toString();
}
return nums;
}

字符串加法

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
private static String add(String str1, String str2)
{

if (str1 == null) return str2;
if (str2 == null) return str1;
StringBuilder sb = new StringBuilder();
// 从最低位开始
int i = str1.length() - 1;
int j = str2.length() - 1;
// 进位计数器
int count = 0;
// 从共有位数开始加
while (i > -1 && j > -1)
{
char c1 = str1.charAt(i--);
char c2 = str2.charAt(j--);
if (c1 == '1' && c2 == '1')
{
if (count == 0)
{
sb.append(0);
count++;
}
else
{
sb.append(1);
}
}
else if (c1 == '1' || c2 == '1')
{
if (count == 0) sb.append(1);
else sb.append(0);
}
else
{
if (count == 0)
{
sb.append(0);
}
else
{
sb.append(1);
count--;
}
}
}
int index = i>-1?i:j;
String str= i>-1?str1:str2;
// 若两个字符串长度不同将会执行下面的加法
while (index > -1)
{
char c = str.charAt(index--);
if (count == 0)
{
sb.append(c);
}
else if (c == '1')
{
sb.append(0);
}
else
{
sb.append(1);
count--;
}
}
// 最后加上进位(如果有)
while (count != 0)
{
sb.append(1);
count--;
}
// 逆序输出
return sb.reverse().toString();
}

迭代累加

1
2
3
4
5
6
7
8
9
10
11
public static String calcSum(String[] nums)
{

if (nums == null || nums.length == 0) return null;
if (nums.length == 1) return nums[0];
String result = null;
for (int i = 0; i < nums.length; i++)
{
result = add(result, nums[i]);
}
return result;
}

面试总结:一开始没弄清面试官的意图,以为是解数学题,浪费很多写代码的时间(当时计时7分钟)。超时依旧没写完,orz。我以为我挂了二面,没想到还是让我过了,就这样,技术面全过了。