标签:.net 软件 seq csdn title des str ret 正整数分解
-- =============================================
-- Author: <maco_wang>
-- Create date: <2011-01-21>
-- Description: <将一个正整数分解为m个2的n次方的和>
-- =============================================
--创建函数
CREATE function GetSumSequence(@num INT)
returns nvarchar(200)
AS
BEGIN
DECLARE @numc INT
SET @numc = @num
DECLARE @numstr VARCHAR(50)
SET @numstr = ‘‘
WHILE ( @num <> 0 )
BEGIN
SET @numstr = @numstr + CONVERT(CHAR(1), @num % 2)
SET @num = @num / 2
END
--SELECT REVERSE(@numstr)
DECLARE @i INT
SET @i = LEN(@numstr)
DECLARE @j VARCHAR(MAX)
SET @j = ‘‘
WHILE ( @i > 0 )
BEGIN
IF ( SUBSTRING(REVERSE(@numstr), LEN(@numstr) - @i + 1, 1) = ‘1‘ )
SELECT @j = @j + ‘+2^‘ + CAST (@i-1 AS VARCHAR(10))
SET @i = @i - 1
END
return (CAST(@numc AS VARCHAR(100)) + ‘=‘ + STUFF(@j, 1, 1, ‘‘))
END
go
--测试示例
select dbo.GetSumSequence(12)
select dbo.GetSumSequence(65)
select dbo.GetSumSequence(892)
select dbo.GetSumSequence(1919191)
--运行结果
/*
12=2^3+2^2
65=2^6+2^0
892=2^9+2^8+2^6+2^5+2^4+2^3+2^2
1919191=2^20+2^19+2^18+2^16+2^14+2^11+2^7+2^6+2^4+2^2+2^1+2^0
*/
标签:.net 软件 seq csdn title des str ret 正整数分解
原文地址:http://www.cnblogs.com/accumulater/p/6244683.html