Lua Programming 4th edition Chapter 13 after-school exercise answers

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作与运算
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))

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 can not do this, I do not want to do

13.7 nausea

Published 80 original articles · won praise 9 · views 10000 +

Guess you like

Origin blog.csdn.net/Icecoldless/article/details/104091199