| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 맛집
- MySQL
- Spring Boot
- elasticsearch
- java
- 후기
- Git
- 스프링
- 리뷰
- jface
- 알고리즘
- boot
- 백준
- effective
- nodejs
- 인터페이스
- javascript
- 엘라스틱서치
- 자바스크립트
- java8
- JPA
- 이펙티브
- Spring
- kibana
- Web
- node
- 독후감
- error
- 자바
- RCP
Archives
- Today
- Total
wedul
문자열 정수를 int 형 정수로 변경하는 atoi 함수를 자바로 구현 본문
반응형
C언어에서 제공하는 atoi 메서드를 자바로 구현해보자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class Main { public static void main(String args[]) { atoi("20"); } public static int atoi(String str) { int radix = 10; byte[] temp = str.getBytes(); int result = 0; for(int i=0;i<temp.length;i++) { if (temp[i] < '0' || temp[i] > '9') { // 0~9 넘어갈경우 (문자 방지) throw new NumberFormatException(); } result = (result*radix) + temp[i] - '0'; System.out.printf("(%s*%s) + %s - '0'", result, radix, temp[i]); System.out.println(); } return result; } } | cs |
계산과정
(2*10) + 50 - '0'
(20*10) + 48 - '0'
temp[i]가 0 ~ 9 사이를 넘어서는 경우에는 숫자가 아니라고 판단되어 오류를 미리 발생한다.
반응형
'JAVA > JAVA 관련' 카테고리의 다른 글
| Java List 인터페이스 중 CopyOnWriteArrayList 소개 (0) | 2018.06.03 |
|---|---|
| java 메모리 누수 주된 원인 (0) | 2018.05.28 |
| HashMap에서 사용되는 인스턴스 객체의 equals()와 hashCode() 재 정의 중요성 (0) | 2018.05.28 |
| 자바 Annotation 만들기 (0) | 2018.05.28 |
| Java Reflection 설명 및 사용법 (0) | 2018.05.28 |
