统计连续1的个数?
问一个问题:任意给一个正整数(2的63次方以内),转化为二进制后,怎么统计其中连续1的最大个数max?
比如:十进制数是3516对应的二进制数是110110111100。那么max就是4
[解决办法]
create function f_int2bin_1(@i int)returns intasbegin declare @s varchar(1000) set @s='' while @i>0 select @s=cast(@i%2 as varchar)+@s,@i=@i/2 declare @s1 as char(1) declare @s2 as char(1) declare @j as int declare @k as int set @j = 0 set @k = 0 set @s1 = '' set @i = 1 while @i <= len(@s) begin set @s2 = substring(@s , @i , 1) if @s2 <> @s1 begin set @s1 = @s2 if @j > @k and @s2 = '0' set @k = @j set @j = 1 end else begin if @i = len(@s) and @s2 = '1' begin if @j + 1 > @k set @k = @j + 1 end else set @j = @j + 1 end set @i = @i + 1 end return @kendgo--调用 select dbo.f_int2bin_1(3516)/*1101101111004*/select dbo.f_int2bin_1(35160)/*10001001010110002*/select dbo.f_int2bin_1(351600)/*10101011101011100003*/drop function dbo.f_int2bin_1
[解决办法]