[面经]CVTE技术二面一道算法题
2016-03-17 09:46
260 查看
题目描述: 1+11+111+…+1111111111=sum,最后一个二进制数是n个1。计算二进制数的累加后sum的值。
思路解析:
1. 首先,这明显是个大数问题。所以建议所有数都用字符串来表示或者是int数组来表示。这里我们用字符串来表示。
2. 使用字符串表示二进制数的话,需要实现两个二进制数字符串形式的加法运算。(关键)
3. 需要有制造这么多个1的字符串数组的方法。
4. 使用循环迭代的方式将二进制数组累加起来。
我们从最简单的方法写起吧,先从”大数制造器”开始。
字符串加法
迭代累加
面试总结:一开始没弄清面试官的意图,以为是解数学题,浪费很多写代码的时间(当时计时7分钟)。超时依旧没写完,orz。我以为我挂了二面,没想到还是让我过了,就这样,技术面全过了。
思路解析:
1. 首先,这明显是个大数问题。所以建议所有数都用字符串来表示或者是int数组来表示。这里我们用字符串来表示。
2. 使用字符串表示二进制数的话,需要实现两个二进制数字符串形式的加法运算。(关键)
3. 需要有制造这么多个1的字符串数组的方法。
4. 使用循环迭代的方式将二进制数组累加起来。
我们从最简单的方法写起吧,先从”大数制造器”开始。
public static String[] createNums(int n){ if(n<=0) return null; StringBuilder sb=new StringBuilder(); String[] nums = new String ; for(int i=0;i<n;i++){ sb.append(1); nums[i]=sb.toString(); } return nums; }
字符串加法
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(); }
迭代累加
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。我以为我挂了二面,没想到还是让我过了,就这样,技术面全过了。
相关文章推荐
- 根据字体多少使UILabel自动调节尺寸
- 内存对齐
- Android studio assets的创建
- Android数据缓存加载,listview显示
- Spring官网下载Spring源码
- 递归_数制转换(十转其他进制)
- 最全的Resharper快捷键汇总
- 利用WPF绘图
- css使用flexbox布局容器内多元素水平居中
- C# 把data的值装换成string型
- 2016年3月7日作业
- 在windows7系统中显示和隐藏系统保留盘
- ORA-01810 格式代码出现两次,日期格式,时间格式,to_date错误
- 从eoeandroid换到CSDN-[回顾]
- LoadRunner12.x简易入门教程--(二)Action迭代
- Mac下OpenCV环境搭建
- aconfigure: error: no acceptable C compiler found in $PATH
- eclipse.ini参数说明
- Ubuntu 14.04 vmware workstation:Virtual ethernet [Failed]
- 在Eclipse添加Android兼容包( v4、v7 appcompat )