文字列を整数に置換-Java

923 ワード

問題の説明


関数を生成し、
  • 文字列sを数値に変換した結果を返します.
  • に答える

    class Solution {
        public int solution(String s) {
            return Integer.parseInt(s);
        }
    }

    他人の解答

    public class StrToInt {
        public int getStrToInt(String str) {
                boolean Sign = true;
                int result = 0;
    
          for (int i = 0; i < str.length(); i++) {
                    char ch = str.charAt(i);
                    if (ch == '-')
                        Sign = false;
                    else if(ch !='+')
                        result = result * 10 + (ch - '0');
                }
                return Sign?1:-1 * result;
        }
        //아래는 테스트로 출력해 보기 위한 코드입니다.
        public static void main(String args[]) {
            StrToInt strToInt = new StrToInt();
            System.out.println(strToInt.getStrToInt("-1234"));
        }
    }