Lua程序设计第4版第13章课后练习答案

13.1

function f131(un,mod)
    print(string.format("%u",un))
    print(string.format("%u",mod))
    local i = 1
    while math.ult(un,i*mod)==false do
        i = i+1
        print(string.format("i = %u,%u",i,i*mod))
    end
    return un-(i-1)*mod
end

print(f131(3<<62>>1,(3<<62>>1)-1))

13.2

function f132(n)
    cnt =0
    while n>0 do
        n = n//10
        cnt= cnt+1
    end
    return cnt==0 and 1 or cnt
end
print(f132(0))

13.3

function f133(n)
    if n-1&n==0 then
        print("是2的幂次方")
        return
    else
        print("不是")
        return
    end
end
f133(133)

13.4
普通的做法,不断的和1比较,然后右移1,是1次数加1

--1作与运算
function f134(n)
    cnt = 0
    while n>0 do
        if n&1==1 then
            cnt = cnt+1
        end
        n = n>>1
    end
    return cnt
end

print(f134(7))

更好的做法
把n和n-1进行与运算,那么n最右边的1一定会变成0,如此循环到后面n一定会变成0.

int BitCount2(n)
{
    c =0 ;
    for (; n; ++c)
    {
        n &= (n -1) ; // 清除最低位的1
    }
    return c ;
}

13.5

--同上求出二进制数
function f135(n)
    s = ""
    while n>0 do
        s = n&1 == 1 and s.."1" or s.."0"
        n = n>>1
    end
    if s==string.reverse(s) then
        print("是回文数")
    else
        print("不是回文数")
    end
end
f135(8)

13.6 做不出来,不想做

13.7 恶心

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JustEasyCode

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值