当前位置:Gxlcms > mysql > 【叶子函数分享四十】将一个正整数分解为m个2的n次方的和

【叶子函数分享四十】将一个正整数分解为m个2的n次方的和

时间:2021-07-01 10:21:17 帮助过:58人阅读

-- ============================================= -- Author: maco_wang -- Create date: 2011-01-21 -- Description: 将一个正整数分解为 m 个 2 的 n 次方的和 -- ============================================= go -- 创建函数 CREATE function GetSum

-- =============================================

-- Author:

-- Create date: <2011-01-21>

-- Description: <将一个正整数分解为m2n次方的和>

-- =============================================

go

--创建函数

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

*/

人气教程排行