/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:使用移位运算来避免乘法运算
* 作 者: 雷恒鑫
* 完成日期: 2012 年 10 月 21 日
* 版 本 号: V1.0
* 对任务及求解方法的描述部分
* 输入描述:移位运算的特点是速度快,使用移位运算来避免乘法运算是一种常用技巧。
不过乘数必须都是正整数,而且必须至少有一个是 2 的 n 次方。例如:
num *= 32;等同于num <<= 5;
2 的 5 次方等于 32
如果乘数不是 2 的 n 次方,则可以把乘数分解成几个 2 的 n 次方的和:
num *= 20;等同于num *= (16 + 4);
* 问题描述:
* 程序输出:
* 程序头部的注释结束
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
enum Color { Red, Yellow, Green }
namespace five_week
{
class Program
{
static void Main(string[] args)
{
double d = shift.calculation(78, 20);
Console.WriteLine("78 * 20 = {0}", d);
Console.ReadKey();
}
}
public static class shift
{
public static double calculation(int x, int y)
{
int yy = 0, xx = x;
ArrayList aList = new ArrayList();
int n = 1, i = 0;
while (true)
{
//n *= 2;
//++i;
if (n > y)
{
n = n / 2;
--i;
yy += x <<= i;
x = xx;
y -= n;
n = 1;
i = 0;
}
if (n == y)
{
yy += x <<= i;
break;
}
if (y == 0)
{
break;
}
n *= 2;
++i;
}
return yy;
}
}
}
运行结果: