首页 > 试题广场 >

平衡数

[编程题]平衡数
  • 热度指数:2413 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
牛牛在研究他自己独创的平衡数,平衡数的定义是:将一个数分成左右两部分,分别成为两个新的数。
左右部分必须满足以下两点:
1,左边和右边至少存在一位。
2,左边的数每一位相乘如果等于右边的数每一位相乘,则这个数称为平衡数。
例如:1221这个数,分成12和21的话,1*2=2*1,则称1221为平衡数,再例如:1236这个数,可以分成123和1*2*3=6,所以1236也是平衡数。而1234无论怎样分也不满足平衡数。

输入描述:
输入一个正整数(int范围内)。


输出描述:
如果该数是平衡数,输出 "YES", 否则输出 "NO"。
示例1

输入

1221
1234

输出

YES
NO
a=raw_input()
flag=False
iflen(a)==1:
    print('NO')
else:
    fori in range(len(a)):
        number=1
        number1=1
        forj in range(0,i+1):
            number=number*int(a[j])
 
        forj in range(i+1,len(a)):
            number1=number1*int(a[j])
 
         
        ifnumber==number1:
            flag=True
     
    if(flag==True):
        print('YES')
    else:
        print('NO')
发表于 2017-03-24 16:45:53 回复(0)
import java.util.Scanner;
import java.lang.*;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int number;				
		int r1;
		int r2;
		while(in.hasNext())
		{
			boolean PHS = false;
			number = in.nextInt();
			String str = String.valueOf(number);
			if (number>=10)
			{
				for (int i = 0; i<str.length()-1; i++)
				{
					r1 = 1;
					r2 = 1;
					for (int j = 0; j<=i;j++)
					{
						String perstr1 = str.substring(j,j+1);
						int num1 = Integer.parseInt(perstr1);
						r1 = r1 * num1;
					}
					for (int k = i+1;k<str.length();k++)
					{
						String perstr2 = str.substring(k,k+1);
						int num2 = Integer.parseInt(perstr2);
						r2 = r2 * num2;
					}
					if (r1 == r2)
					{
						PHS = true;
						break;
					}
				}
				if (PHS)
				{
					System.out.println("YES");
				}
				else
				{
					System.out.println("NO");
				}
			}
			else
			{
				System.out.println("NO");
			}
		}		
	}
}


发表于 2017-03-24 10:10:09 回复(0)
#include<iostream>
using namespace std;

int function(int n){
	int sum[15], i = 0, j = 0;
	while (n){
		sum[i] = n % 10;
		n /= 10;
		i++;
	}
	if (--i <= 0)
		return 0;
	int left = sum[j], right = sum[i];
	while (j < i - 1){    //线性遍历
		if (left <= right && left != 0)
			left *= sum[++j];
		else
			right *= sum[--i];
	}
	if (left == right)
		return 1;
	else
		return 0;
}
int main(){
	int n;
	while (cin >> n){
		if (function(n) == 1)
			cout << "YES";
		else
			cout << "NO";
	}
	return 0;
}//时间复杂度为O(n的位数)

编辑于 2017-03-24 17:43:25 回复(0)
通过简单的字符串的截取
    Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        if (str.length() < 2) {
            System.out.println("NO");
        } else {
            boolean isBlanceNum = false;
            for (int i = 1; i < str.length(); i++) {
                String before = str.substring(0, i);
                String after = str.substring(i);
                int mulVal_bef = Integer.parseInt(before.substring(0, 1)),
                    mulVal_aft = Integer.parseInt(after.substring(0, 1));
                for (int j = 1; j < before.length(); j ++) {
                    mulVal_bef *= Integer.parseInt(before.substring(j, j + 1));
                }
                for (int j = 1; j < after.length(); j ++) {
                    mulVal_aft *= Integer.parseInt(after.substring(j, j + 1));
                }
                if (mulVal_bef == mulVal_aft) {
                    isBlanceNum = true;
                    break;
                }
            }
            System.out.println(isBlanceNum ? "YES" : "NO");
        }
        in.close();

发表于 2017-04-05 17:29:56 回复(0)

//

//  323t1.cpp

//

//

//  Created byyori  on 17/3/23.

//

//

#include <stdio.h>

#include <iostream>

#include <algorithm>

#include <vector>

using namespace std;

int main(){

    int n;

    while (cin>>n){

        bool flag = 0 ;

        vector< int > vec;

        int count = 0 ;

        while (n) {

            count++;

            vec.push_back(n% 10 );

            n/= 10 ;

        }

        if (count < 2 ){

            cout<< "NO" <<endl;

            break ;

        }

        cout<<count<<endl;

        reverse(vec.begin(),vec.end());

        for ( int i = 1 ;i < count;i++){

            vector< int > leftvec(vec.begin(),vec.begin()+i),rightvec(vec.begin()+i,vec.end());

            int left = 1 ,right = 1 ;

            for ( int j = 0 ;j < leftvec.size();j++)

                left *= leftvec[j];

            for ( int j = 0 ;j < rightvec.size();j++)

                right *= rightvec[j];

            if (left == right){

                cout<< "YES" <<endl;

                flag = 1 ;

                break ;

            }

        }

        if (!flag)

            cout<< "NO" <<endl;

    }


}


发表于 2017-03-24 22:55:49 回复(0)
import java.util.Scanner;

/**
 * Created by Scruel on 2017/3/23.
 * Personal blog : http://blog.csdn.net/scruelt
 * Github : https://github.com/scruel
 */
public class BalanceString {
        public static void main(String[] args) {

                Scanner input = new Scanner(System.in);
                int n = input.nextInt();
                String s = String.valueOf(n);
                if (s.length() < 2) {
                        System.out.println("NO");
                        return;
                }
                char[] chars = s.toCharArray();
//                System.out.println(s);

                int[] sum1 = new int[chars.length];
                sum1[0] = chars[0] - 48;
                for (int i = 1; i < chars.length; i++) {
                        sum1[i] = (chars[i] - 48) * sum1[i - 1];
                }
                int[] sum2 = new int[chars.length];
                sum2[0] = chars[chars.length - 1] - 48;
                for (int i = 1; i < chars.length; i++) {
                        sum2[i] = (chars[chars.length - i - 1] - 48) * sum2[i - 1];
                }
                int p = chars.length - 1, q = chars.length - 1;
                while (p >= 0 && q >= 0) {
                        if (sum1[p] < sum2[q]) {
                                q--;
                        } else if (sum1[p] > sum2[q]) {
                                p--;
                        } else if (p + q == chars.length - 2) {
                                System.out.println("YES");
                                return;
                        } else {
                                int tempP = p;
                                int tempQ = q;
                                while (tempP >= 0) {
                                        if (sum1[tempP] != sum2[q])
                                                break;
                                        else if (tempP + q == chars.length - 2) {
                                                System.out.println("YES");
                                                return;
                                        } else {
                                                tempP--;
                                        }
                                }
                                while (tempQ >= 0) {
                                        if (sum1[p] != sum2[tempQ])
                                                break;
                                        else if (p + tempQ == chars.length - 2) {
                                                System.out.println("YES");
                                                return;
                                        } else {
                                                tempQ--;
                                        }
                                }
                                q--;
                                p--;
                        }
                }
                System.out.println("NO");
        }
}

编辑于 2017-03-24 16:59:21 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main()
{
	int temp;
	while(cin>>temp)
	{
		
		vector<int > vec;
		while(temp)
		{
			int aa;
			aa=temp%10;
			vec.push_back(aa); //按位放入数组中
			temp=temp/10;
		}
		int n=vec.size();
		int i=0;
		int bValue=1;
		int eValue=1;
		int flag=0;
		for(i=1;i<n-1;i++)
		{
			for(int j=0;j<=i-1;j++) //计算前部分的乘积
			{
				
				bValue=bValue*vec[j];
			}
			for(int k=n-1;k>=i;k--)//计算后部分的乘积

			{
				
				eValue=eValue*vec[k];
			}
			if(eValue==bValue ) //相等则输出“YES”
			{
				cout<<"YES"<<endl;
				flag=1;
				break;
			}
			eValue=1; //每次运算将乘积初始化
			bValue=1;
		}
		if(flag==0)
		{
			cout<<"NO"<<endl; //不成功输出“NO”
		}

	}
	return 0;
}

编辑于 2017-03-24 15:43:30 回复(0)
shein笔试
#include <iostream>
#include<vector>
using namespace std;

int main() {
    int a;
    cin>>a;
    if(a<10){//个位数直接判否
        cout<<"NO";
        return 0;
    }
    vector<int> ans;
    int cout0=0;//记录各个位上的0的个数
    
    //按位存入vector
    while(a){
        int cur = a%10;
        if(!cur)cout0++;
        if(cout0==2){//至少两个0,直接判是
            cout<<"YES";
            return 0;
        }
        ans.push_back(cur);
        a/=10;
    }
    if(cout0==1){//只有一个0,直接判否
        cout<<"NO";
        return 0;
    }
    int i=0, j=ans.size()-1;
    int sum1=ans[i], sum2=ans[j];
    //双指针两头向中间处理
    while(i<j){
        if(i+1==j){//指针相遇,结束循环
            break;
        }
        if(sum1<sum2){
            sum1*=ans[++i];
        }else if(sum1>sum2){
            sum2*=ans[--j];
        }else {
            if(i+2==j){//双指针之间还有一个数未遍历
                sum1*=ans[++i];
            }else {
                sum1*=ans[++i];
                sum2*=ans[--j];
            
            }
        
        }
    }
    if(sum1==sum2)cout<<"YES";
    else cout<<"NO";
}

编辑于 2023-08-09 17:05:01 回复(0)
def fn(str):
    s=1
    for i in range(len(str)):
        s=s*str[i]
    return  s
def solution (sta):
    k =0
    for j in range(len(sta)-1):
        if fn(sta[:j+1])==fn(sta[j+1:]):
            k+=1
    if k==0:
        return "NO"
    else:
        return "YES"
a=input()
str1=[]
for i in range (len(a)):
    str1.append(int(a[i]))
print(solution(str1))
发表于 2022-08-29 22:27:21 回复(0)
#python3
from functools import reduce
str=input()
nums=list(map(int,str))
result='NO'
for i in range(1,len(nums)):
    rl=nums[0:i]
    ll=nums[i:]
    r=reduce(lambda x, y:x*y,rl)
    l=reduce(lambda x, y:x*y,ll)
    if r==l:
        result='YES'
        break
print(result)
编辑于 2022-08-29 16:38:40 回复(0)
// javascript暴力解法
while(line = readline()) {
    print(numCheck(line))
}

function numCheck(num) {
    if(num.length === 0) return 'NO'
    let str = num.toString()
    let len = num.length
    let returnStr = 'NO'
    for(let i = 1; i < num.length; i ++) {
        let left = str.substring(0, i)
        let rigth = str.substring(i, len)
        // console.log('======', left, rigth)
        let leftNum = 1
        let rightNum = 1
        for(let j = 0; j < left.length; j ++) {
            leftNum = leftNum * parseInt(left[j])
        }
        for(let z = 0; z < rigth.length; z ++) {
            rightNum = rightNum * parseInt(rigth[z])
        }
        // console.log('+++++++++', leftNum, rightNum)
        if(leftNum === rightNum) return returnStr = 'YES'
    }
    return returnStr
}
发表于 2022-08-29 16:06:34 回复(0)
import sys
try:
    while True:
        a = input()
        z = 'NO'
        if len(a) == 1:
            print('NO')
        else:
            for i in range(len(a)):
                m = 1
                n = 1
                for j in a[:i]:
                    m *= int(j)
                for k in a[i:]:
                    n *= int(k)
                if m == n:
                    z = 'YES'
                    break
            print(z)
except:
    pass

发表于 2020-03-19 22:33:14 回复(0)
while(num=parseInt(readline())){
    var arr = num.toString().split('');
    if(arr.length > 1){
    for(var i=0;i<arr.length-1;i++){
        var b =arr.slice(0,i+1);
        var c = arr.slice(i+1);
        var resb = 1;
        var resc = 1;
        for(var k in b){
            resb = resb * b[k];
        }
        for(var n in c){
            resc = resc * c[n];
        }
        if(resb == resc){
            console.log('YES');
            break;
        }else if((i==arr.length-2) && (resb!=resc)){
            console.log('NO');
        }
    }
    }else {
        console.log('NO');
    }
}
发表于 2019-03-11 14:33:06 回复(0)
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.nextLine();
            if(str.length() <2){
                System.out.println("NO");
            }else{
                boolean flag = false;
                int length = str.length();
                for(int i=1;i<length;i++){//长度在1~length-1之间
                    int leftMul = 1;
                    int rightMul = 1;
                    for(int j=0;j<i;j++){//左右两边的断点在i位置,所以左边为0~i-1,右边为i~length-1。
                        leftMul *= Integer.parseInt(str.substring(j,j+1)); 
                    }
                    for(int k=i;k<length;k++){
                        rightMul *= Integer.parseInt(str.substring(k,k+1));
                    }
                    if(leftMul == rightMul){
                        flag = true;
                        break;
                    }
                }
                System.out.println(flag?"YES":"NO");
            }
        }
        sc.close();
    }
}

发表于 2018-08-17 15:57:08 回复(0)
python解法:滑动窗口
importsys
fromfunctools importreduce
fori insys.stdin.readlines():
    forj,v inenumerate(i.strip()):
        ifj!=0:
            left=i.strip()[:j]
            right=i.strip()[j:]
            ifreduce(lambdax,y:x*y,map(int,list(left)))==reduce(lambdax,y:x*y,map(int,list(right))):
                print('YES');break
    else:print('NO')
发表于 2018-07-19 00:56:48 回复(0)
vs2005测试了有用,但是这里一直说itoa函数没有定义。

 思路就是:先将输入转成字符串,根据字符串长度,遍历字符串,将字符串分解成两个部分。 再对两个部分分别进行乘积相加。进行比较。
这个排版真是一言难尽

int GetpinghenData(char *str)
{  int i = 0, ret = 1;  int len = strlen(str);  for(i = 0; i < len; i++)  {  ret *= *(str + i) - '0';  }  return ret;
}


int main()
{  int data;  cin >> data;  char str[25] = {0};  char str1[25] = {0};  char str2[25] = {0};  itoa(data, str, 10); /* 这个函数会说没定义*/  int i = 0, len = strlen(str);  for(i = 0; i < len-1; i++)  {  strcpy(str1, str);  str1[i+1] = 0;  strcpy(str2, str + i + 1);  if(GetpinghenData(str1) == GetpinghenData(str2))  {  cout << "Yes" << endl;  return 0;  }  }  cout << "No" << endl;  return 0;
}

编辑于 2018-02-26 14:43:55 回复(0)
public class Main {
    public static void main(String[] args) {
        java.util.Scanner in = new java.util.Scanner(System.in);
        String str = in.nextLine();
        if (str == null || str.length() == 0) {
            System.out.println("请输入参数");
            return;
        }
        System.out.println(isBalance(str) ? "YES" : "NO");
    }
    private static boolean isBalance(String num) {
        if (num.length() < 2) {
            return false;
        }
        //检测0,如果一个0,为false;如果多个0,为true
        int firstZero = num.indexOf('0');
        if (firstZero > -1) {
            int lastZero = num.lastIndexOf('0');
            if (firstZero == lastZero) {
                return false;
            } else {
                return true;
            }
        }
        //左右两边计算乘积,值小的一方移位
        char[] arr = num.toCharArray();
        int left = 0, right = arr.length - 1, leftv = arr[left] - 48, rightv = arr[right] - 48;
        while (left < right - 1) {
            if (leftv <= rightv) {
                leftv *= arr[++left] - 48;
            } else {
                rightv *= arr[--right] - 48;
            }
        }
        return leftv == rightv;
    }
}
编辑于 2018-01-25 20:43:14 回复(0)
a = raw_input()
num = int(a)

b = map(int, list(str(a)))
result = 'NO'
if len(b)<=1:
    result = 'NO'
else:
    for i in range(1,len(b)):
        head = 1
        tail = 1
        h = b[0:i]
        t = b[i:len(b)]
        for i in h:
            head *= i
        for i in t:
            tail *= i
        if head==tail:
            result = 'YES'
            break
print result

发表于 2018-01-11 22:11:42 回复(0)


public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    String num=sc.next();
    int a[]=new int[num.length()];
    for(int i=0;i<num.length();i++){
        a[i]=Integer.parseInt(String.valueOf(num.charAt(i)));
    }
    boolean key=false;
    int mul1=1,mul2=1;
    for(int i=0;i<a.length;i++){
        for(int k=i;k>=0;k--){
            mul1*=a[k];
        }
        for(int j=i;j<a.length-1;j++){
            mul2*=a[j+1];
        }
        if(mul1==mul2){
            key=true;
        }
        }
    if(key){
        System.out.println("YES");
    }else{
        System.out.println("NO");
    }
}


编辑于 2017-12-16 13:53:30 回复(0)
import java.util.Scanner;

public class Main {

public static void main(String[] args){
checkBalanceNumber();
}

/**
     * 查找平衡数
     * 例如 1236中   1*2*3   = 6所以是平衡数
     */
    private static void checkBalanceNumber(){
        Scanner scanner = new Scanner(System.in);
        while(true){
            String num = scanner.next();
            if(!num.equals("exit")){
                int len = num.length();
                if(len<2){
                    System.out.println("NO");
                    continue;
                }
                int[] integers = new int[len];
                for(int i =0;i<len;i++){
                    try{
                        integers[i] = Integer.parseInt(num.substring(i,i+1));
                    }catch(Exception e){
                        scanner.close();
                        return ;//注意这里要关闭流,避免后面再次关闭导致异常
                    }
                }
                boolean isBalanceNum = false;
                for(int i=1;i<len - 1;i++){
                    int left = integers[0];
                    for(int j=1;j<=i;j++){
                        left *= integers[j];
                    }
//                    System.out.print("left" +left);
                    int right = integers[i+1];
                    for(int z=i+2;z<len;z++){
                        right *= integers[z];
                    }
//                    System.out.print("right" +right);
                    if(left == right){
                        isBalanceNum = true;
                        break;
                    }
                }
                if(len == 2&&integers[0] == integers[1]){
                    isBalanceNum = true;
                }
                if(!isBalanceNum){
                    System.out.println("NO");
                }else{
                    System.out.println("YES");
                }
            }else{
                break;
            }
        }
        scanner.close();
    }

}
编辑于 2017-10-11 11:08:38 回复(0)

热门推荐

通过挑战的用户

平衡数