笔试题:输入一串数字,进行逆序输出。比如:输入-1234,输出-4321。逆序输出后的数字超越范围,则返回0。

package com.spring.demo.controller;
/**
 * 逆序(逆序输出输入的数字,并且如果逆序后值越界,则返回0)
 * @author wxe
 * @since 1.0.0
 */
public class Test {

    public static void main(String[] args) {
        String inputStr = "+344454547";
        System.out.println(reverse(inputStr));

    }
    
    public static int reverse(String inputStr){
        String outBuff = "";
        int length = inputStr.length();
        Stack stack = new Stack(length);
        
        for (int i = 0; i < length; i++) {
            stack.push(inputStr.charAt(i));
        }
        
        while (!stack.isEmpty()) {
            char ele = stack.pop();
            outBuff = outBuff + ele;
        }
        
        char lastChar = outBuff.charAt(length-1);
        outBuff = lastChar + outBuff.substring(0, length-1);//截取掉最后一位符号位
        
        int result ;
        try {
            result = Integer.parseInt(outBuff);  //防止越界
        } catch (Exception e) {
            return 0;
        }
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
            return 0;
        }
        return result;
        
    }
    /**
     * 内部类,栈
     * @author wxe
     * @since 1.0.0
     */
    static class Stack {
        private int maxSize;//容纳的最大元素
        private char[] elementData;  //存储元素的内存空间
        private int top ; //指向栈顶元素
        
        public Stack(int maxSize){
            this.maxSize = maxSize;
            elementData = new char[maxSize];
            top = -1;
        }
        
        public void push(char obj){
            elementData[++top] = obj;
        }
        
        public char pop(){
            if (isEmpty()) {
                throw new RuntimeException("已满栈!");
            }
            
            return elementData[top--];
        }
        
        public boolean isEmpty(){
            return top == -1;
        }
        
    }

}

 

 posted on 2017-08-30 10:51  abysstoabyss  阅读(91)  评论(0)    收藏  举报