總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。

2016年8月16日 星期二

【Codility】考題Decimal ZIP problem

/*
The decimal zip of two non-negative integers A and B is an integer C whose
 decimal representation is created from the decimal representations
 of A and B as follows:

• the first (i.e. the most significant) digit of C is the first digit of A;
• the second digit of C is the first digit of B;
• the third digit of C is the second digit of A;
• the fourth digit of C is the second digit of B;
• etc.

 If one of the integers A and B runs out of digits, the remaining digits of
 the other integer are appended to the result.

 The decimal representation of 0 is assumed to be "0".

 For example, the decimal zip of 12 and 56 is 1526.
 The decimal zip of 56 and 12 is 5162.
 The decimal zip of 12345 and 678 is 16273845.
 The decimal zip of 123 and 67890 is 16273890.

 Write a function: function solution(A, B); that, given two non-negative
 integers A and B, returns their decimal zip.

 The function should return -1 if the result exceeds 100,000,000.

 For example, given A = 12345 and B = 678 the function should return
 16273845, as explained above.
 */

package com.java.test;

//you can also use imports, for example:
//import java.util.*;

//you can write to stdout for debugging purposes, e.g.
//System.out.println("this is a debug message");

class Solution1 {
public static void main(String[] args){
System.out.println("Input A=12 , B=56 ");
solution(12,56);
System.out.println("Input A=12345 , B=678 ");
solution(12345,678);
System.out.println("Input A=123 , B=67890 ");
solution(123,67890);
}
 public static int solution(int A, int B) {
     // write your code in Java SE 8
     if(A > 100000000 || B > 100000000){
    System.out.println("the result exceeds 100,000,000");
    return -1;
     }
     if(A < 0 || B < 0){
    System.out.println("A or B is non-negative integer");
    return -1;
     }

     String str_a =  String.valueOf(A);
     String str_b =  String.valueOf(B);
     String result = "";
   
     for(int i = 0 ; i < str_a.length() || i < str_b.length(); i++){
   
         if(i < str_a.length()){
             result = result + str_a.charAt(i);
         }
         if(i < str_b.length()){
             result = result + str_b.charAt(i);
         }
     }
     System.out.println("Ouput : "+result);
     return Integer.parseInt(result);
 }
}

/*

 */

沒有留言:

張貼留言