javajava-8logic

lowest value for given number


I recently gave a codility test. There was a this question which I couldn't solve. Now that I'm trying at home, I would like to get help. I don't remember the complete question language, but I do remember the output how would the program respond. Here we go.

"write a java program, for a given number N, need to find the lowest number for the given N. N could be a billion number too." {this may not be the exact one, Sorry about that}

For Example:

  1. N=1 then o/p is 0.

  2. N=123 then o/p is 100

  3. N=1234 then o/p is 1000 and so on.

My Solution: --just a workaround, this isn't actual logic.

class Solution {
    public int solution(int N) {
        int pointer=0;
        if (N == 1) {
            return 0;
        } else {
            String digitsCount = Integer.toString(N); 
            for(int i = 0; i < digitsCount.length(); i++) {
                pointer++;
            }
            StringBuffer subString = new StringBuffer();
            int count=0;
            while(count < pointer-1) {
                subString.append("0");
                count++;
            }
            subString = subString.insert(0, "1");
            return Integer.parseInt(subString.toString());
        }
    }
}

Solution

  • Here is the updated code.

    private static long solution(long N) {
            if (N == 1) {
                return 0;
            } else {
                String digitsCount = Long.toString(N); 
                int pointer=digitsCount.length();
                StringBuilder subString = new StringBuilder();
                subString.append("1");
                for(int i=0; i<pointer-1; i++) {
                    subString.append("0");
                }
                return Long.parseLong(subString.toString());
            }
        }