读书人

微软面试题_六

发布时间: 2012-11-19 10:18:51 作者: rapoo

微软面试题_6
题目:编程实现两个正整数的除法。例如:60 / 10 = 6
分析:此题容易想到的方法是用10(除数)累加,统计累加到60(被除数)时的个数。但如果是100000 / 1的情况,累加次数会变得很大。此题较好的方法是采用贪心算法,如果每次用10 * 2 ^ n进行累加,算法效率会有很大的提高。

public static int dividend( int x, int y ) {int result = 0;int multi;while( y <= x ) {multi = 1;while( y * multi <= ( x >> 1 ) ) {multi <<= 1;}result += multi;x -= multi * y;}return result;}

读书人网 >编程

热点推荐