Frage im Vorstellungsgespräch bei Google

Function for int2str

Antworten zu Vorstellungsgespräch

Anonym

12. Feb. 2011

public static String int2str(int x) { if (x == 0) return "0"; StringBuilder res = new StringBuilder(); while (x > 0) { res.insert(0, (char)('0' + x % 10)); x /= 10; } return res.toString(); }

Anonym

12. Feb. 2011

Important to note that insertion at postion 0 everytime will require shifting of string and that will be O(n) for each insertion and o(n2) effectively. Why not insert at end and after exiting loop reverse string. Both of these will be 0(n).