滴滴出行2017秋招笔试编程题(一)——连续最大和、末尾0的个数、进制转换
2017-01-07 16:08
260 查看
这题比较简单,算法过程就是遍历数组,记录到第i个数的连续最大和,在计算第i个数的连续最大和时,先判断到第i-1个数的连续最大和是正还是负,如果是负数,则到第i个数的连续最大和就是第i个数本身;如果是正数,则到第i个数的连续最大和就是到第(i-1)个数的连续最大和加上第i个数。代码如下:
public class MaxSubArray { public static int FindGreatestSumOfSubArray(int[] array,int n) { if(array == null || n == 0) return 0; int sum = Integer.MIN_VALUE; int curSum = 0; for(int i = 0; i < n; i++){ if(curSum <= 0) curSum = array[i]; else curSum += array[i]; if(curSum > sum) sum = curSum; } return sum; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner cin = new Scanner(System.in); int n; int array[] = new int[100005]; while(cin.hasNext()){ n = cin.nextInt(); for(int i = 0 ;i < n; i++){ array[i] = cin.nextInt(); } System.out.println(FindGreatestSumOfSubArray(array,n)); } } }
以上代码在牛客网90%的测试用例通过,我用c++按这个思路写100%通过,后来发现牛客网的最后一个测试案例有问题。
这个题目一看就是大数问题,果然也被大数坑了好几次,思路是一边进行阶乘,一边计算末尾零的个数,同时把计算过的0去掉。但是光去掉零并不能使数字小多少,计算时间也没有少很多。其实两个数字相乘末尾零的个数只与这两个数字末尾的几位数字有关,这样我们就可以大胆地将乘数对100000大胆取余,一下把数字降了好几个数量级。代码如下:
public class countZero { public static void main(String args[]){ Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int result = 1; int count = 0; for(int i = 1;i <= n;i++){ result *= i; if(result % 10 == 0){ count++; result = result / 10; } if(result > 100000) result = result % 100000; } while(result % 10 == 0){ count++; result = result/10; } System.out.println(count); } }
这个题代码按照题目说的转化就好了
public class convertDec { public static void main(String args[]){ Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int m = cin.nextInt(); String str = convert(n,m); for(int i = str.length() - 1; i >= 0; i--){ System.out.print(str.charAt(i)); } } static char ch[] = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z'}; public static String convert(int n,int m){ String str = ""; while(n != 0){ int num = n % m; str += String.valueOf(ch[num]); n = n / m; } return str; } }
在牛客网测试用例通过70%,提示数组越界非法访问,但是最后实在没找出来。
相关文章推荐
- 2017滴滴秋招笔试编程题-求连续子数组的最大和
- 滴滴出行2017秋招笔试真题-编程题汇总 - 题解
- 给定整数序列求连续子串最大和 - 滴滴出行2018校园招聘内推笔试-研发工程师
- 百度2017春招笔试真题编程题集合:买帽子 [python]
- 腾讯2017秋招笔试编程题
- 网易笔试题:求和最大的连续子串
- 腾讯2017秋招笔试编程题:geohash [python]
- 滴滴出行2017秋招算法笔试题(作弊概率)
- [编程题] 末尾0的个数 滴滴笔试
- 【牛客网】滴滴出行2017秋招测试岗笔试真题汇总
- 百度2017春招笔试真题编程题集合--Python
- 腾讯2017秋招笔试编程题(二)----游戏任务标记
- 腾讯2017秋招笔试编程题(三)---素数对
- 两种排序方法(字典序,strcmp的用法)----网易2017内推笔试编程题合集(二)
- 赶去公司--网易2017春招实习笔试编程题2
- 调整队形--网易2017春招实习笔试编程题3
- 百度2017春招笔试真题编程题集合之买帽子
- 腾讯2017秋招笔试编程题--游戏任务标记
- 网易2017春招笔试编程题 分饼干
- 名企笔试:好未来2017秋招笔试(连续最长的数字串)