10 Things New Android Developers Can Relate To
30+ Bite-Sized Pro Tips to Become a Better Android Developer
[code language=”delphi”]
// 1 -> 0
// 0 -> 1
function flip(g: integer): integer;
begin
result := 1 xor g;
end;
// 1 – positive
// 0 – negative
function sign(f: integer): integer;
begin
result := flip((f shr 31) and $1);
end;
function getMax(a, b: integer): integer;
var
k, q: integer;
begin
k := sign(a – b);
q := flip(k);
result := a * k + b * q;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
a, b: integer;
begin
a := strtoint(Edit1.Text);
b := strtoint(Edit2.Text);
Edit3.Text := inttostr(getMax(a, b));
end;
[/code]
but
if a=maxint-3, b=-20 then there is a integer overflow.
solution
[code language=”delphi”]
function getMax(a, b: integer): integer;
var
k, q, c, sa, sb, sc: integer;
signofa: integer;
signofc: integer;
begin
c := a – b;
sa := sign(a);
sb := sign(b);
sc := sign(c);
signofa := sa xor sb;
signofc := flip(sa xor sb);
k := signofa * sa + signofc * sc;
q := flip(k);
result := a * k + b * q;
end;
[/code]
Compare without if, case, <, >
[code language=”delphi”]
var
a, b: word;
a1, b1: word;
begin
a := abs(strtoint(Edit1.Text));
b := abs(strtoint(Edit2.Text));
a1 := a div b;
a1 := ((a1 + 2) div (a1 + 1)) mod 2;
b1 := (a1 + 1) mod 2;
Edit3.Text := inttostr(a*a1+b*b1) + ‘ >= ‘ + inttostr(a*b1+b*a1);
end;
[/code]
[code language=”delphi”]
procedure TForm1.Button1Click(Sender: TObject);
var
a, b: integer;
begin
a := strtoint(Edit1.Text);
try
try
b := a div a;
except
on e: Exception do
b := 0;
end;
finally
Edit3.Text := inttostr(b);
end;
end;
[/code]