剑指 Offer 20. 表示数值的字符串
这种大模拟题真的就是磨练心态的,太麻烦了,wa得没脾气。
总结起来就是一定要有数字,小数点前必须有数字并且小数点前面不能有e,e前面必须有数字且前面不能有e,有e之后为了有指数,需要重置\(numCnt\),符号必须出现在第一位或者在e后面。
class Solution {
public boolean isNumber(String s) {
if(s == null || s.length() == 0) {
return false;
}
s = s.trim();
int eCnt = 0, numCnt = 0, dotCnt = 0, symbolCnt = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c >= '0' && c <= '9') {
// 出现数字直接加
numCnt++;
} else if(c == '.') {
// 出现小数点,需要之前没有出现过.和e
if(dotCnt != 0 || eCnt != 0) {
return false;
} else {
dotCnt++;
}
} else if(c == 'e' || c == 'E') {
// 出现了e,需要之前出现了数字且没有出现过e
if(numCnt == 0 || eCnt != 0) {
return false;
} else {
eCnt++;
numCnt = 0;
}
} else if(c == '+' || c == '-') {
// 符号要出现在第一位
if(i != 0 && (s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E')) {
return false;
} else {
symbolCnt++;
}
} else {
return false;
}
}
return numCnt > 0;
}
}
推荐这些技术文章:
#include <stdio.h>
int main(){
int a = 1 ,b = 1;
if(1 == (a&b)){
printf("都是1:true.\n");
}else{
printf("都是1:false.\n");
}
return 0;
}
执行
都是1:true.
#include <stdio.h>
...
写一个判断素数的函数,在主函数输入一个整数,输出是否是素数的消息。
#include<stdio.h>int test(int x){ int i=1; for(i=1;i<x;i++){ if(x%i==0&&x>2) return 0; else return 1; }
}int main(){ int test(int x); int b; ...
class Solution {
public boolean less(String s, String t) {
return s.charAt(0) < t.charAt(0);
}
public String largestGoodInteger(String num) {
if(num.length() <= 2...
int f(int x)
{
int t = x, y = 0;
while (t)
{
y = y * 10 + t % 10;
t /= 10;
}
if (x == y) return true;
return false;
}
...
class Solution {
public int countValidWords(String sentence) {
boolean flag = true;
String [] strs = sentence.split(" ");
int count=0;int gen=0;
for(int i=0;i<strs.length;i++) {
...
题目描述
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
方法一:直接利用String的特性
public boolean isValid(String s) {
while (s.contains("()") || s.c...
求如何用python判断输入数字是否为素数,我这种方法不知道为什么不行,求大神帮忙。
问题
最佳回答
运用python的数学函数
import math
def isPrime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
单行程序扫描素数
f...
private void txtWgt_KeyPress(object sender, KeyPressEventArgs e)
{
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e...
class Solution {
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]){
return num...
【LeetCode】剑指 Offer II 006. 排序数组中两个数字之和
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int length=numbers.size();
int left,right,cpl=length-1,m;
int flag=0;
vector<in...
文章链接:https://www.dianjilingqu.com/51016.html
本文章来源于网络,版权归原作者所有,如果本站文章侵犯了您的权益,请联系我们删除,联系邮箱:saisai#email.cn,感谢支持理解。