18 lines Java clean code


  • 0
    S
    class Solution {
        public int maximumSwap(int num) {
            int ret = num;
            String s = num + "";
            for (int i = 0; i < s.length(); i++) {
                for (int j = 0; j < i; j++) {
                    ret = Math.max(ret, swap(s, i, j));
                }
            }
            return ret;
        }
        private int swap(String s, int i, int j) {
            StringBuilder sb = new StringBuilder(s);
            sb.setCharAt(i, s.charAt(j));
            sb.setCharAt(j, s.charAt(i));
            return Integer.valueOf(sb.toString());
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.