Integer/String Conversions

本文介绍了一种字符串与整数相互转换的方法。首先通过解析字符数组将字符串转换为整数,考虑到负号的存在,并确保转换后的数值正确。然后介绍了整数转回字符串的过程,包括处理负数情况和构建字符串表示形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Integer/String Conversions

Write two conversion routines. The first routine converts a string to a signed integer. You may assume that the string only contains digits and the minus character (‘-’), that it is a properly formatted integer number, and that the number is within the range of an int type. The second routine converts a signed integer stored as an int back to a string.



class Solution {
  public static int strToInt(String s) {
    boolean isNeg = false;
    char[] str = s.toCharArray();
    int i = 0;
    if (str[0] == '-') {
      isNeg = true;
      i = 1;
    }
    
    int num = 0;
    while (i < s.length()) {
      num = num * 10;
      num = num + (str[i++] - '0');
    }
    
    if (isNeg) {
      num = num * (-1);
    }
    
    return num;
    
  }
  
  
  public static String IntToStr(int num) {
    boolean isNeg = false;
    int i = 0;
    int len = 0;
    

    
    int numTemp = num;
    if (num < 0) {
      num = num * -1;
      isNeg = true;
      len++;
    }
    
    do {
      numTemp = numTemp/10;
      len++;
    } while (numTemp != 0);
    
    char[] temp = new char[len];
    
    do {
      temp[i++] = (char)((num % 10) + '0');
      num = num / 10;
    } while (num != 0);
    
    StringBuilder b = new StringBuilder();
    if (isNeg) {
      b.append('-');
    }
    
    while (i > 0) {
      b.append(temp[--i]);
    }
    System.out.print(len);
    return b.toString();
    
    
  }
  public static void main(String[] args) {
    
    
    int number = -2000;
    String str = IntToStr(number);
    System.out.print(str);
  }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值