计算器出错:把所有的‘0’都变成了‘*’,而且不能智能的消除小数点数字后多余的0。
比如100.00100写成了1**.**1**,现在要求编程序转换回来,并消除小数点后多余的零。
如输入:1.**1**
输出:1.001
#include<iostream> #include<string> using namespace std; /* 悬赏题 */ class Solution { public : string Convert(string str) { bool flag = false; //标记是否有小数点 if( str.empty() ) { return str; } for(int i = 0;i < str.size();i++) //先变换 { if(str[i] == '.') { flag = true; continue; } if(str[i] == '*') { str[i] = '0'; } } int count = 0; if(flag) { for(int i = str.size() - 1;str[i] == '0';i--) //记录无效0的个数 { ++count; } } //cout << str << endl; str = str.substr(0,str.size() - count); return str; } }; int main() { // your code goes here string str; Solution A; while(cin >> str) { cout << A.Convert(str) << endl; } return 0; }
public class Replace { public String replace(String number){ if(number==null||number.equals("")){ return null; } number=number.replaceAll("\\*", "0");//特殊字符,需要正则表达式 boolean isContains=containsPoint(number); if(isContains){ char[] charNum=number.toCharArray(); int len=number.length(); int count=0; for(int i=len-1;i<len;i--){ if(charNum[i]!='0'){ break; } else{ count++; } } number=number.substring(0,len-count); } return number; } //是否包含小数点 public boolean containsPoint(String number){ boolean isContains=true; String[] num=number.split("\\."); isContains=num.length>1?true:false; return isContains; } }
import java.util.Scanner; public class RToZ{ public String Chrysan(String str){ str = str.replaceAll("[*]", "0"); if(str.indexOf(".") > 0){ str = str.replaceAll("0+?$", ""); } return str ; } public static void main(String[] args) { System.out.print("请输入:"); Scanner s = new Scanner(System.in); String str = s.next(); str =new RToZ().Chrysan(str); System.out.print("调整为:"); System.out.println(str); } }
string recover(string *ch) { int len=(*ch).length(); if(len==0) return "\0"; int i=0; while(i<len&&(*ch)[i]!='.') //首先处理小数点‘.’前面的数字 { if((*ch)[i]=='*') (*ch)[i]='0'; i++; } if(i<=len-1) //如果i的值没有到最后,说明有小数点,下面就对小数点后面的数字处理 { i=len-1; while((*ch)[i]!='.') //从最后一位往前处理数字,如果出现零就删除元素,如果出现非零则终止循环 { if((*ch)[i]=='*') (*ch).pop_back(); else break; i--; } while ((*ch)[i]!='.') //因为已经找到小数点位置,则此后的数字就直接把*转换为0就ok了 { if((*ch)[i]=='*') (*ch)[i]='0'; i--; } } return *ch; }
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int main() { string str; int i, index; cin >> str; for(i = 0; i != str.size(); i++) { if(str[i] == '*') { str[i] = '0'; } } index = str.find_last_not_of('0'); str = str.substr(0, index + 1); // index要加1,[1, index+1)区间 cout << str << endl; return 0; }