日期:2014-05-20 浏览次数:20787 次
public class StrToInt { public int Change(String str) { if (str.length() <= 0) { return -1; } char ch = str.charAt(0); int tmp = 0; switch (ch) { case 48: tmp = 0; break; case 49: tmp = 1; break; case 50: tmp = 2; break; case 51: tmp = 3; break; case 52: tmp = 4; break; case 53: tmp = 5; break; case 54: tmp = 6; break; case 55: tmp = 7; break; case 56: tmp = 8; break; case 57: tmp = 9; break; default: return 0; } if (str.length() == 1) { return tmp; } String tmpStr = str.substring(1); if (str.charAt(0) == 45) return -(tmp * (int) Math.pow(10, tmpStr.length()) + Change(tmpStr)); else return tmp * (int) Math.pow(10, tmpStr.length()) + Change(tmpStr); } public static void main(String[] args) { // TODO Auto-generated method stub StrToInt s = new StrToInt(); System.out.println(s.Change("120345")); } }
------解决方案--------------------
参考c atoi的代码,我用了char,与int两个数组,转换我不太明白,望高手解答
#include <ctype.h> #include <stdio.h> int main() { int i; int a[100]={0}; //char *s; //gets(s); char *s="12312"; atoi1(s,a); for(i=0;i<strlen(s);i++) { printf("%d",a[i]); } system("pause"); return 0; } void atoi1 (char *s,int a[]) { int i=0; while(s[i]!='\0') { a[i]=s[i]-'0'; i++; } }
------解决方案--------------------
成功解决了这个问题
#include <ctype.h> #include <stdio.h> int main() { int i; int a[100]={0}; char *s="12312"; int sum=0; int ren=1; atoi1(s,a); for(i=0;i<strlen(s);i++) { printf("%d\n",a[i]); } for(i=strlen(s)-1;i>=0;i--) { sum=sum+(a[i])*ren; ren=ren*10; } printf("%d\n",sum); system("pause"); return 0; } void atoi1 (char *s,int a[]) { int i=0; while(s[i]!='\0') { a[i]=s[i]-'0'; i++; } }