Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个函数将中文数字转成数字 #343

Open
lgwebdream opened this issue Jul 6, 2020 · 2 comments
Open

实现一个函数将中文数字转成数字 #343

lgwebdream opened this issue Jul 6, 2020 · 2 comments
Labels
JavaScript teach_tag 微软 company 编程题 teach_tag

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added JavaScript teach_tag 微软 company 编程题 teach_tag labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@GolderBrother
Copy link

function transformChar(str) {
	// 九十二
	const numChar = {
		'零': 0,
		'一': 1,
		'二': 2,
		'三': 3,
		'四': 4,
		'五': 5,
		'六': 6,
		'七': 7,
		'八': 8,
		'九': 9,
	};
	const levelChar = {
		'十': 10,
		'百': 100,
		'千': 1000,
		'万': 10000,
		'亿': 100000000
	};
	let arr = Array.from(str);
	console.log(arr);
	let sum = 0, temp = 0;
	for(let i = 0; i < arr.length; i++) {
		const char = arr[i];
		if(char === '零') continue;
		if(char === '亿' || char === '万') {
			sum += temp * levelChar[char];
			temp = 0;
		}else {
			const next = arr[i + 1];
			if(next && next !== '亿' && next !== '万') {
				temp += numChar[char] * levelChar[next];
				i++;
			}else {
				temp += numChar[char]
			}
		}
	}
	console.log(`sum`, sum);
	console.log(`temp`, temp);
	return sum + temp;
}

// 1230963897
console.log(transformChar('一十二亿三千零九十六万三千八百九十七'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 微软 company 编程题 teach_tag
Projects
None yet
Development

No branches or pull requests

2 participants