Coding Exercise – LUA Programming – SPOJ Online Judge – Bit XOR


The problem is from SPOJ Online Judge [description here]

bscxor Coding Exercise - LUA Programming - SPOJ Online Judge - Bit XOR beginner code implementation LUA programming language math programming languages SPOJ online judge

Since the input of p and q is restricted to 0 and 1, so we can just check its string value. Bit XOR equals to one if and only if both operands are different.

1
2
3
4
5
6
s = io.read()
if string.sub(s, 1, 1) ~= string.sub(s, 3, 3) then
    print(1)
else
    print(0)
end
s = io.read()
if string.sub(s, 1, 1) ~= string.sub(s, 3, 3) then
	print(1)
else
	print(0)
end

Here, we use string.sub(s, i, j) to get a substring of s starting index i and ending index j. Noted that the index starts at 1 instead of 0.

We can also use bit32.bxor(a, b) to obtain the bit xor for both integers, which you will need to split the input string and convert them into number using tonumber() function.

1
2
3
4
5
6
7
8
9
10
function split(s, delimiter)
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end
 
ss = split(io.read(), " ")
io.write(bit32.bxor(tonumber(ss[1]), tonumber(ss[2])))
function split(s, delimiter)
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

ss = split(io.read(), " ")
io.write(bit32.bxor(tonumber(ss[1]), tonumber(ss[2])))

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
277 words
Last Post: Coding Exercise - LUA Programming - SPOJ Online Judge - Test Integer
Next Post: The Two Sum Algorithm using HashMap in C++/Java

The Permanent URL is: Coding Exercise – LUA Programming – SPOJ Online Judge – Bit XOR

Leave a Reply