一个很有用的自定义函数(判断自然数是否包含2的指定次幂)
一个很有用的自定义函数(判断自然数是否包含2的指定次幂) /*
Name : Fun_WheIncluded
Function : 判断选定的数字是否在给定的整数中
可以知道任何一个自然数都可以拆分成若干个2的幂的和,如:
1 = 2^0
2 = 2^1
3 = 2^0 + 2^1
4 = 2^2
5 = 2^0 + 2^2
6 = 2^1 + 2^4
7 = 2^0 + 2^1 + 2^2
8 = 2^3
9 = 2^0 + 2^3
10 = 2^1 + 2^3
11 = 2^0 + 2^1 + 2^3
12 = 2^2 + 2^3
13 = 2^0 + 2^2 + 2^3
14 = 2^1 + 2^2 + 2^3
15 = 2^0 + 2^1 + 2^2 + 2^3
16 = 2^4
17 = 2^0 + 2^4
将任意一个数解析为2的幂的和的方法——递归
规律:
如给定 14
∵ 2^3 < 14 < 2^4
∴ 14中必有8——2^3
14 - 8 = 6
∵ 2^2 < 6 < 2^3
∴ 6中必有4——2^2
6 - 4 = 2
∵ 2 = 2
∴ 14 = 2^3 + 2^2 + 2^1
Parameters : @TotalNum
Type: INT
@SpecifiedNum
Type: INT
Steps :
Author : Waxdoll Cheung
Date : 2005-03-21
*/
CREATE FUNCTION
dbo.Fun_WheIncluded
(
@TotalNum INT,
@SpecifiedNum INT
)
RETURNS BIT AS
BEGIN
DECLARE @varRet BIT
DECLARE @varLoop INT
SET @varLoop = 0
WHILE (@TotalNum >= CAST(POWER(2, @VarLoop) AS INT))
SET @varLoop = @varLoop + 1
SET @TotalNum = @TotalNum - CAST(POWER(2, @varLoop - 1) AS INT)
IF (@varLoop = @SpecifiedNum + 1)
SET @varRet = 1
ELSE
BEGIN
IF (@TotalNum >= 1)
RETURN dbo.Fun_WheIncluded(@TotalNum, @SpecifiedNum)
ELSE
SET @varRet = 0
END
RETURN @varRet
END