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

来源:互联网 发布:php注册登录系统 编辑:程序博客网 时间:2024/06/06 06:38

题目描述: 1+11+111+…+1111111111=sum,最后一个二进制数是n个1。计算二进制数的累加后sum的值。
思路解析:
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[n];        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。我以为我挂了二面,没想到还是让我过了,就这样,技术面全过了。

1 0
原创粉丝点击